python词典的更新方法不起作用

时间:2014-10-30 14:08:26

标签: python dictionary

我有两本词典。

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'

这两种方法有什么区别,为什么第一种不起作用?

3 个答案:

答案 0 :(得分:6)

update方法更新dict 就地。它返回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)的内容,正如您已经注意到的那样,从两个组件构建一个新的dict,而不是更新现有的一个。

答案 1 :(得分:3)

dict.update()会返回None,就像大多数修改容器的方法一样(list.append()list.sort()set.add()等等。这是设计的,所以你不要误以为它会创建一个新的dict(或list等)。

答案 2 :(得分:1)

作为一个新的Python用户,这是一个非常频繁的"陷阱"对我来说,因为我似乎总是忘记它。

正如您猜测的那样,a.update(b)会返回None,就像a.append(b)会返回None列表一样。这些方法更新了的数据结构

假设您实际上不想修改a,请尝试以下操作:

from copy import deepcopy
c = deepcopy(a)
c.update(b)
type(c)  #returns a dict
print(a)
print(b)
print(c)

应该这样做。另一种方式:

c = dict(a,**b)
type(c)  #returns a dict

IMO要好得多。这里发生的事情是b正在被解压缩,所以实际做的是这样的:

c = dict(a, cd=3, ed=5)
type(c)  #returns a dict

如果这样做,请注意,如果a中的任何密钥在b中重复,则其值将被替换,例如:

a = {"ab":3, "bd":4}
c = dict(a, ab=5)
c  #returns  {"ab":5, "bd":4}