我有两本字典。
a = {"ab":3, "bd":4}
b = {"cd":3, "ed":5}`
我想将它们组合成 {'bd': 4, 'ab': 3, 'ed': 5, 'cd': 3}
。
作为this说,a.update(b)
可以完成它。但是当我尝试时,我得到:
type(a.update(b)) #--> type 'NoneType'
谁能给我解释一下为什么我无法获得 dict 类型?
我也试过这个,效果不错:
type(dict(a,**b)) #-->type 'dict'
这两种方法有什么区别,为什么第一种方法不起作用?
最佳答案
update
方法更新字典就地。它返回 None
,就像 list.extend
一样。要查看结果,请查看您更新的字典。
>>> a = {"ab":3, "bd":4}
>>> b = {"cd":3, "ed":5}
>>> update_result = a.update(b)
>>> print(update_result)
None
>>> print(a)
{'ed': 5, 'ab': 3, 'bd': 4, 'cd': 3}
如果您希望结果是第三个单独的字典,则不应使用 update
。使用类似 dict(a, **b)
的东西,正如您已经注意到的那样,它从两个组件构造一个新的字典,而不是更新其中一个现有的。
关于python - python字典的更新方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26655230/