1 #增: 2 dic = {"c":2,"d":6,"f":9} 3 dic["a"] = 12 #字典中存在键,则改值.不存在则直接添加 4 print(dic) 5 dic.setdefault("b",13) #字典中键存在则找键,并返回键的值,键不存在则创建,值默认值为None 6 print(dic)
结果对照:
{'c': 2, 'd': 6, 'f': 9, 'a': 12}
{'c': 2, 'd': 6, 'f': 9, 'a': 12, 'b': 13}
1 #删 2 del dic["a"] #根据指定键删除 3 print(dic) 4 dic.pop("b") #根据指定键弹出字典,,并返回被删除的值 5 print(dic) 6 dic.popitem() #随机删除一组键值对,并返回该键值对.python3.6以上默认删除最后一个 7 print() 8 dic.clear() #清空字典 9 print(dic)
结果对照:
{'c': 2, 'd': 6, 'f': 9, 'b': 13}
{'c': 2, 'd': 6, 'f': 9}
{'c': 2, 'd': 6}
{}
1 #改 2 dic = {} 3 dic2 = {"a":12} 4 dic.update(dic2) #把括号中的字典键值更新到update前面的字典中 5 print(dic) 6 dic["a"] = 18 #字典中存在键,则改值.不存在则直接添加 7 print(dic)
结果对照:
{'a': 12}
{'a': 18}
1 #查 2 dic = {'c': 2, 'd': 6, 'f': 9, 'a': 12, 'b': 13} 3 print(dic.get("c","0")) #返回指定键的值,如果值不在字典中返回默认None,可指定默认值 4 for i in dic.keys(): #查看字典中键 5 print(i) 6 for i in dic.values(): #查看字典中值 7 print(i) 8 for i in dic.items(): #查看字典中的键值对 9 print(i)
结果对照:
2
c
d
f
a
b
2
6
9
12
13
('c', 2)
('d', 6)
('f', 9)
('a', 12)
('b', 13)
1 dic = {} 2 dic = dic.fromkeys(('name', 'age', 'sex'),"哈哈") #迭代生成字典,默认的值为None 3 print(dic)
结果对照:
{'name': '哈哈', 'age': '哈哈', 'sex': '哈哈'}