通过更新现有字典来创建新字典

fro*_*h03 2 python dictionary python-2.7

我想通过更新现有字典来创建新字典。这表现得像假设:

x = {'a': 1}
x.update({'a': 2})
Run Code Online (Sandbox Code Playgroud)

但是为什么下面的结果是 NoneType?

({'a': 1}).update({'a': 2})
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

所有Python标准库回报就地操作Nonedict.update()也不例外。

你不能创建一个dict文字并调用.update()它并期望它返回更新的dict对象,不。

你基本上是这样做的:

tmp = {'a': 1}
result = tmp.update({'a': 2})
del tmp
Run Code Online (Sandbox Code Playgroud)

并期望result成为字典。

可以使用:

dict({'a': 1}, **{'a': 2})
Run Code Online (Sandbox Code Playgroud)

并得到一个合并的字典,但是。或者,对于更实用的版本:

copy = dict(original, foo='bar') 
Run Code Online (Sandbox Code Playgroud)

创建字典的副本并设置一些额外的键(替换该键的任何先前值)。

在 Python 3.5 及更新版本中,您将使用:

copy = {**original, 'foo': 'bar'}
Run Code Online (Sandbox Code Playgroud)