字典操作

a.增加

 >>> info["stu1104"] = "abc"
>>> info
{'stu1102': 'x5456', 'stu1104': 'abc', 'stu1103': 'Mali', 'stu1101': 'Wu'}

b.修改

 >>> info['stu1101'] = "xinge"
>>> info
{'stu1102': 'x5456', 'stu1103': Mali', 'stu1101': 'xinge'}

c.删除

 >>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}
>>> info.pop("stu1101") #标准删除姿势
'武藤兰'
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
>>> del info['stu1103'] #换个姿势删除
>>> info
{'stu1102': 'LongZe Luola'}
>>>
>>>
>>>
>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除
>>> info.popitem()
('stu1102', 'LongZe Luola')
>>> info
{'stu1103': 'XiaoZe Maliya'}

d.查找

 >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
>>>
>>> "stu1102" in info #标准用法
True
>>> info.get("stu1102") #获取
'LongZe Luola'
>>> info["stu1102"] #同上,但是看下面
'LongZe Luola'
>>> info["stu1105"] #如果一个key不存在,就报错,get不会,不存在只返回None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'stu1105'

e.获取键值

 #values
>>> info.values()
dict_values(['LongZe Luola', 'XiaoZe Maliya']) #keys
>>> info.keys()
dict_keys(['stu1102', 'stu1103'])

f.合并

 #update
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
>>> b = {1:2,3:4, "stu1102":"龙泽萝拉"}
>>> info.update(b)
>>> info
{'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}

g.深copy

 import copy
   
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
   
n4 = copy.deepcopy(n1)

h.循环

 #方法1
for key in info:
    print(key,info[key])
 
#方法2
for k,v in info.items(): #会先把dict转成list,数据里大时莫用
    print(k,v)
05-11 10:50