标签:序列 添加 update copy 重复 结果 value rom strong
1 info={"k1":"v1","k2":"v2"} 2 v=info.setdefault("k3",123) 3 print(info,v) 4 #结果:{‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘, ‘k3‘: 123} 123
字典dict
1 info={"k1":"v1",1:"v2",True:"v3"} 2 print(info) 3 #结果:{‘k1‘: ‘v1‘, 1: ‘v3‘}
1 info={"k1":18,2:True,"k3":[11,22,33,{‘kk1‘:‘vv1‘,‘kk2‘:‘vv2‘,‘kk3‘:(99,66)}],"k4":(11,22,33,44)} 2 v=info["k3"][3]["kk3"][0] 3 print(v) 4 #结果:99
1 info={"k1":"v1",2:True,(12,"dd"):[1,2,3]} 2 for item in info.values(): 3 print(item) 4 #结果:v1 5 # True 6 # [1, 2, 3]
-若要获取键值对,则使用dict类的item()方法,例:
1 info={"k1":"v1",2:True,(12,"dd"):[1,2,3]} 2 for k,v in info.items(): 3 print(k,v) 4 #结果:k1 v1 5 # 2 True 6 # (12, ‘dd‘) [1, 2, 3]
1 info={"k1":"v1","k2":"v2"} 2 info.clear() 3 print(info) 4 #结果:{}
1 info={"k1":"v1","k2":"v2"} 2 info2=info.copy() 3 print(info2) 4 #结果:{‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘}
1 v=dict.fromkeys([4,"abc",True],123) 2 print(v) 3 #结果:{4: 123, ‘abc‘: 123, True: 123}
1 info={"k1":"v1","k2":"v2"} 2 v=info.get("k3",444) 3 print(v) 4 #结果:444
1 info={"k1":"v1","k2":"v2"} 2 v=info.pop("k1",444) 3 print(info,v) 4 #结果:{‘k2‘: ‘v2‘} v1
若指定的key不存在,返回参数2指定的value值,例:
1 info={"k1":"v1","k2":"v2"} 2 v=info.pop("k3",444) 3 print(info,v) 4 #结果:{‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘} 444
1 info={"k2":"v2","k1":"v1","k3":"v3"} 2 k,v=info.popitem() 3 print(info,k,v) 4 #结果:{‘k2‘: ‘v2‘, ‘k1‘: ‘v1‘} k3 v3
1 info={"k1":"v1","k2":"v2"} 2 v=info.setdefault("k1",123) 3 print(info,v) 4 #结果:{‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘} v1
若key不存在,添加key并设置值,返回设置后key对应的值,例:
1 info={"k1":"v1","k2":"v2"} 2 v=info.setdefault("k3",123) 3 print(info,v) 4 #结果:{‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘, ‘k3‘: 123} 123
info={"k1":"v1","k2":"v2"} info.update({"k1":1,"k3":3}) print(info) #结果:{‘k1‘: 1, ‘k2‘: ‘v2‘, ‘k3‘: 3}
1 info={"k1":"v1","k2":"v2"} 2 info.update(k1=1,k3=3) 3 print(info) 4 #结果:{‘k1‘: 1, ‘k2‘: ‘v2‘, ‘k3‘: 3}
标签:序列 添加 update copy 重复 结果 value rom strong
原文地址:https://www.cnblogs.com/hm-blog/p/9925981.html