问题描述
在 Python 中,我试图创建一个由 2 个独立词典 (dict1
& dict2
) 组成的列表.但是,当我使用 append 和 update 方法将它们添加到新列表时,它似乎改变了我的 dict1
字典.
In Python, I'm trying to create a list consisting of 2 independent dictionaries (dict1
& dict2
). However, when I add them both to a new list using append and update methods, it seems to change my dict1
dictionary.
n = []
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4, "e": 5}
n.append(dict1)
n[0].update(dict2)
这给了我想要的 n
结果,但它也覆盖了我的 dict1
,这是不想要的.
This gives me result I want for n
but it also overwrites my dict1
, which is not desired.
dict1
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
为什么会这样?如何在不修改第一个字典的情况下实现将 2 个字典加入列表的目标?此代码用于将 2 个 JSON 文档合并为一个,以防万一有人想知道.
Why is this happening? How can I achieve my goal of joining the 2 dicts into a list without modifying my first dict? This code serves the purpose of joining 2 JSON docs into one, in case anyone is wondering.
推荐答案
正如评论中提到的,当你执行 .update()
时,你引用了同一个字典.因此,您可以使用 .copy()
进行显式复制并获得可以更新的初始字典.
As mentioned in comments, you are referencing the same dict when you do the .update()
. So you can use .copy()
to do an explicit copy and get an initial dict that can then be updated.
n.append(dict1.copy())
n[0].update(dict2)
或者如果你有两个字典,你可以在一行中完成:
Or if you have two dicts, you can do it in one line like:
n.append(dict(dict1, **dict2))
或者你可以明确地从一个空的字典开始,然后像::
Or you can explicitly start with an empty dict, and then update like::
n.append({})
n[0].update(dict1)
n[0].update(dict2)
这篇关于将多个字典添加到列表时不需要的字典更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!