字典处理方法
dic = {"k1" : "aaa", "k2" : "bbb", "k3" : 111, "k4" : 222}
dict.fromkeys(*args, **kwargs) (根据序列创建一个字典,并赋予统一的值,如不传入值默认赋予None)
dic = dict.fromkeys(['a', 'b', 'c'],'love')
print(dic)
输出:{'a': 'love', 'b': 'love', 'c': 'love'}
.setdefault(key, d) (如果key存在,返回key的value值,如果不存在,添加key和d)
v = dic.setdefault('k5', 333)
print(dic)
print(v)
输出:{"k1" : "aaa", "k2" : "bbb", "k3" : 111, "k4" : 222, "k5" : 333}
输出:333
.update() (可以修改字典内的value,也可以增加一个新的键值对)
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 删除
del dic["k1"]
print(dic)
输出:{"k2" : "bbb", "k3" : 111, "k4" : 222}
.pop(key, d) (删除指定key,如果没有该key,则返回d)
dic.pop('k4')
print(dic)
输出:{"k1" : "aaa", "k2" : "bbb", "k3" : 111}
.popitem() (删除最后一个)
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
.values() (用for循环可以输出value)
for value in dic.values():
print(value)
输出:aaa
bbb
111
222
.keys() (用for循环可以输出key,默认for循环就是输出key)
.items() (用for循环可以同时输出key:value)
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
.get(key, d) (根据key获取value,不存在时返回None或返回传入的d)
value = dic.get('k5', '没有这个key')
print(value)
输出:没有这个key