将多个词典添加到列表时不需要的词典更新 [英] Unwanted Dictionary Update When Adding Multiple Dictionaries to a List

查看:96
本文介绍了将多个词典添加到列表时不需要的词典更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我试图创建一个包含2个独立字典( dict1 和amp; 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个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))

或者您可以明确地从一个空的dict开始,然后像这样进行更新:

Or you can explicitly start with an empty dict, and then update like::

n.append({})
n[0].update(dict1)
n[0].update(dict2)

这篇关于将多个词典添加到列表时不需要的词典更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆