标签:clear block fileinput checked update dism idea boa atl
字典
# 一
dic = {‘name‘:‘江子牙‘,‘age‘:21}
print(dic,type(dic))
# 二
dic1 = dict(name=‘江子牙‘,age=21)
print(dic1)
# 三
dic2 = {}
print(dic2,type(dic2))
# 增加
dic = {‘name‘:‘江子牙‘,‘age‘:21}
# 存在则修改,不存在,则添加
dic[‘sex‘] = ‘男‘
print(dic)
dic.setdefault(‘closed‘,‘停用‘)
print(dic)
# 存在key,不做任何改变。不存在则添加。
dic.setdefault(‘name‘,‘小喵喵‘)
print(dic)
# 删除
dic = {‘name‘: ‘江子牙‘, ‘age‘: 21, ‘sex‘: ‘男‘, ‘closed‘: ‘停用‘}
# 有返回值 没有key时就会报错 最好在后面加None
dic.pop(‘closed‘)
print(dic)
# 随机删除 返回(key,value) 无意义
res = dic.popitem()
print(res)
print(dic)
# del 不存在就会报错
del dic[‘name‘]
print(dic)
# clear() 清空字典
dic.clear()
print(dic)
dic1 = {‘name‘: ‘江子牙‘, ‘age‘: 21, ‘sex‘: ‘男‘, ‘closed‘: ‘停用‘}
print(dic1.pop(‘删除‘,‘不存在‘))
dic1.pop(‘删除‘)
# 总结:最好通过pop来删除 不存在时可以通过设置返回值还不会报错
# 改
# update()
d1 = {‘name‘:‘alex‘,‘age‘:18}
d2 = {‘name‘:‘‘,‘sex‘:1,‘age‘:22}
d2.update(d1)
# 覆盖添加
print(d2)
d2.update(name=1,age=2)
print(d2)
d2.update({‘sex‘:‘男‘})
print(d2)
# 查
d = {‘name‘: ‘江子牙‘, ‘age‘: 21, ‘sex‘: ‘男‘}
print(d.keys()) # 返回列表
print(d.values()) # 返回列表
print(d.items()) # 返回列表,里面是元祖
print(d.get(‘name‘))
print(d.get(‘aaa‘))
print(d.get(‘aaa‘,‘不存在‘))
# 可通过for循环来对上述结果来进行查询。
for key in d:
print(key)
for key in d.keys():
print(key)
for key,value in d.items():
print(key,value)
总结:首选get
标签:clear block fileinput checked update dism idea boa atl
原文地址:https://www.cnblogs.com/xjmlove/p/10127213.html