我想通过更新现有字典来创建一个新字典。这表现得像预期的那样:
x = {'a': 1}
x.update({'a': 2})
但是为什么下面的结果是 NoneType 呢?
({'a': 1}).update({'a': 2})
最佳答案
所有 Python标准库中的就地操作返回None
,dict.update()
也不异常(exception)。
您不能创建 dict
文字并在其上调用 .update()
并期望它返回更新后的 dict
对象,不。
你实际上是在这样做:
tmp = {'a': 1}
result = tmp.update({'a': 2})
del tmp
并期望 result
是字典。
你可以使用:
dict({'a': 1}, **{'a': 2})
然后得到一个合并的字典。或者,对于更实用的版本:
copy = dict(original, foo='bar')
创建字典的副本并设置一些额外的键(替换该键的任何先前值)。
在 Python 3.5 及更高版本中,您将使用:
copy = {**original, 'foo': 'bar'}
关于python - 通过更新现有字典创建新字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24820145/