Python 字典 增删改查 字典复制 两个字典连接
>>> b
{'a': 97, 'c': 99, 'b': 98, 'd': 100}
>>> b['e']=101 #增加元素
>>> b
{'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100}
>>> b.pop('b') #删除元素
98
>>> b
{'a': 97, 'c': 99, 'e': 101, 'd': 100}
>>> b['c']=500 #修改元素
>>> b
{'a': 97, 'c': 500, 'e': 101, 'd': 100}
>>> b['d'] #查询元素
100
>>>
=======================================
>>> b
{'a': 97, 'c': 500, 'e': 101, 'd': 100}
>>> del b['a'] #另外一种删除元素的方法
>>> b
{'c': 500, 'e': 101, 'd': 100}
>>>
=======================================
>>> b
{'c': 500, 'e': 101, 'd': 100}
>>> a={}
>>> a
{}
>>> a=b.copy() #字典的复制
>>> a
{'c': 500, 'e': 101, 'd': 100}
>>> b
{'c': 500, 'e': 101, 'd': 100}
>>> id(a)
40649472
>>> id(b)
40826464
>>>
=======================================
把两个字典连接在一起
有个update()方法,不过如果key相同的话,会用后者的key-value覆盖前者的。 D.update(E, **F) -> None. Update D from dict/iterable E and F. If E has a .keys() method, does: for k in E: D[k] = E[k] If E lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] 例子: >>> a = {3: 5, 4: 6} >>> b = {4: 8, 7: 9} >>> a.update(b) >>> a {3: 5, 4: 8, 7: 9}