字典的增删改查
增:
# 增:没有就增加 有就替换
dic = {'name':'zzc','age':18}
dic['hight']=185
print(dic)
dic['name']='zzx'
print(dic)
# setdefault的使用
dic.setdefault('weight',130)
print(dic)
结果:
删:
# 删:1.pop() 按key删除,有返回值
dic = {'name':'zzc','age':18,'height':180}
dic.pop('name')
# 2.clear 清空
dic = {'name':'zzc','age':18,'height':180}
dic.clear()
# 3.del 删除,有返回值
dic = {'name':'zzc','age':18,'height':180}
del dic['name']
# 4.popitem()随机删除 有返回值
dic = {'name':'zzc','age':18,'height':180}
dic.popitem()
print(dic)
结果:改:
# 改: update
dic = {'name':'zzc','age':18,'height':180}
dic.update({'name':'zzx'})
print(dic)
结果:查:
# 查:1.dic.keys() dic.values() dic.itema()
dic = {'name':'zzc','age':18,'height':180}
print(dic.keys())
print(dic.values())
print(dic.items())
# 2.for循环去查
dic = {'name':'zzc','age':18,'height':180}
for k,v in dic.items():
print(k,v)
结果: