标签:添加 for循环 key 返回 for 创建 统一 方法 get
dic = {"k1" : "aaa", "k2" : "bbb", "k3" : 111, "k4" : 222}
dic = dict.fromkeys([‘a‘, ‘b‘, ‘c‘],‘love‘)
print(dic)
输出:{‘a‘: ‘love‘, ‘b‘: ‘love‘, ‘c‘: ‘love‘}
v = dic.setdefault(‘k5‘, 333)
print(dic)
print(v)
输出:{"k1" : "aaa", "k2" : "bbb", "k3" : 111, "k4" : 222, "k5" : 333}
输出:333
dic = {"k1" : "aaa", "k2" : "bbb", "k3" : 111, "k4" : 222}
dic.update(k1 = 111, k3 = "aaa", k5 = "ccc") #也可以传入字典,如{‘k1‘:111, ‘k3‘:‘aaa‘, ‘k5‘:‘ccc‘}
print(dic)
输出:{"k1" : 111, "k2" : "bbb", "k3" : "aaa", "k4" : 222, "k5" : "ccc"}
del dic["k1"]
print(dic)
输出:{"k2" : "bbb", "k3" : 111, "k4" : 222}
dic.pop(‘k4‘)
print(dic)
输出:{"k1" : "aaa", "k2" : "bbb", "k3" : 111}
dic = {"k1" : "aaa", "k2" : "bbb", "k3" : 111, "k4" : 222}
k, v = dic.popitem()
print(dic)
print(k, v)
输出:{"k1" : "aaa", "k2" : "bbb", "k3" : 111}
输出:k4 222
for value in dic.values():
print(value)
输出:aaa
bbb
111
222
for value in dic.items():
print(value)
输出:(‘k1‘ : ‘aaa‘)
(‘k2‘ : ‘bbb‘)
(‘k3‘ : 111)
(‘k4‘ : 222)
for k, v in dic.items():
print(k, v)
输出:k1 aaa
k2 bbb
k3 111
k4 222
value = dic.get(‘k5‘, ‘没有这个key‘)
print(value)
输出:没有这个key
标签:添加 for循环 key 返回 for 创建 统一 方法 get
原文地址:https://www.cnblogs.com/lzh0769/p/10660697.html