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

all*_*ang 1 python dictionary

我有两本词典.

a = {"ab":3, "bd":4}
b = {"cd":3, "ed":5}` 
Run Code Online (Sandbox Code Playgroud)

我想把它们结合起来{'bd': 4, 'ab': 3, 'ed': 5, 'cd': 3}.

由于说,a.update(b)可以完成它.但是当我尝试时,我得到:

type(a.update(b)) #--> type 'NoneType'
Run Code Online (Sandbox Code Playgroud)

有谁愿意向我解释为什么我不能获得字典类型?

我也试过这个,它做得很好:

type(dict(a,**b)) #-->type 'dict'
Run Code Online (Sandbox Code Playgroud)

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

Hen*_*ter 6

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}
Run Code Online (Sandbox Code Playgroud)

如果您希望结果是第三个单独的字典,则不应使用update.使用类似的东西dict(a, **b),正如您已经注意到的那样,从两个组件构造一个新的dict,而不是更新现有的一个.


Ric*_*ica 3

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

正如您所猜测的,a.update(b)返回None,就像a.append(b)返回None列表一样。这些类型的方法(是另一种)就地list.extend更新数据结构。

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

c = dict(a)  # copy a
c.update(b)  # update a using b
type(c)  #returns a dict
Run Code Online (Sandbox Code Playgroud)

应该可以做到这一点。

另一种更短的方法:

c = dict(a,**b)
type(c)  #returns a dict
Run Code Online (Sandbox Code Playgroud)

这里发生的事情是b正在拆包。仅当 的键b都是字符串时,这才有效,因为您实际上正在做的是:

c = dict(a, cd=3, ed=5)
type(c)  #returns a dict
Run Code Online (Sandbox Code Playgroud)

请注意,对于上述任何方法,如果 中的任何键在a中重复b,则该b值将替换该a值,例如:

a = {"ab":3, "bd":4}
c = dict(a, ab=5)
c  #returns  {"ab":5, "bd":4}
Run Code Online (Sandbox Code Playgroud)