python - 通过更新现有字典创建新字典

标签 python python-2.7 dictionary

我想通过更新现有字典来创建一个新字典。这表现得像预期的那样:

x = {'a': 1}
x.update({'a': 2})

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

({'a': 1}).update({'a': 2})

最佳答案

所有 Python标准库中的就地操作返回Nonedict.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/

相关文章:

python - 缩短这个特定的代码

python - 从数据框中打印单个日期字符串

python - 类型错误 : read_excel() takes exactly 2 arguments (1 given)

c - C 语言字典

python - 将混合数据类型字典中的 float 转换为 int

python - 使用引用号搜索文件

python - 在 jupyter notebook 中加载 spacy 时出现 ImportError

python - 寻找最接近给定值的路径旅行成本

python - base 64(GNU/Linux 与 python)

python - 如何使用 Flask/Jinja2 将 Python 字典转换为 HTML 模板