简体   繁体   English

Python 设置嵌套字典中键相同时的键值

[英]Python setting values for keys in nested dictionaries when keys are the same

Really simple situation but I can't seem to find the answer anywhere.非常简单的情况,但我似乎无法在任何地方找到答案。 I have a dictionary that contains a bunch of other dictionaries that I'm using to store configurations.我有一本字典,其中包含我用来存储配置的一堆其他字典。 Each nested dictionary is created from the same template, so the keys are the same.每个嵌套字典都是从同一个模板创建的,因此键是相同的。 When trying to set a key in one of them, the same key across all the nested dictionaries gets updated with the value.当尝试在其中一个中设置键时,所有嵌套字典中的相同键都会使用该值更新。

Here's an example of the kind of thing I'm doing.这是我正在做的事情的一个例子。

my_dict = {
    "bar": {
        "baz": None,
        "qux": None
    },
    "foo": {
        "baz": None,
        "qux": None
    }
}

my_dict['foo']['baz'] = True

Then the dictionary looks like this, I don't understand why?然后字典是这样的,我不明白为什么? I'm sure I've done this kind of thing fine before as well which is why its confusing.我敢肯定我以前也做过这种事情,这就是为什么它令人困惑。

{
    "bar": {
        "baz": True,
        "qux": None
    },
    "foo": {
        "baz": True,
        "qux": None
    }
}

EDIT编辑

The nested dictionaries are created using a template like this:嵌套字典是使用这样的模板创建的:

temp = {'baz': None,
        'qux': None}
 
my_dict['foo'] = temp
my_dict['bar'] = temp

Any help would be greatly appreciated, Thank You任何帮助将不胜感激,谢谢

You need to use the copy method in order to copt a dict type without them being related to each others:您需要使用copy方法来复制dict类型而不使它们相互关联:

my_dict = {}

temp = {'baz': None,
        'qux': None}
 
my_dict['foo'] = temp.copy()
my_dict['bar'] = temp.copy()

print(my_dict)
my_dict['foo']['baz'] = True
print(my_dict)

Output: Output:

{'bar': {'baz': None, 'qux': None},
 'foo': {'baz': None, 'qux': None}}

{'bar': {'baz': None, 'qux': None},
 'foo': {'baz': True, 'qux': None}}

Note: You don't need to call .copy() twice in this case, because you're not using temp elsewhere in your code.注意:在这种情况下,您不需要调用.copy()两次,因为您没有在代码的其他地方使用temp So it changing it's content is fine as long as you have another dict that does use .copy() .因此,只要您有另一个使用.copy()的字典,它就可以更改其内容。

Your problem occurs because you're pointing my_dict['foo'] and my_dict['bar'] to the same object.出现问题是因为您将my_dict['foo']my_dict['bar']指向同一个 object。 So once that object is changed, the value for both will be changed.因此,一旦更改了 object,两者的值都会更改。

On top of what Ann has, you could try using this since your dictionary is shallow:除了 Ann 所拥有的,你可以尝试使用它,因为你的字典很浅:

my_dict = {}

temp = {'baz': None,
        'qux': None}
 
my_dict['foo'] = dict(temp)
my_dict['bar'] = dict(temp)

print(my_dict)
my_dict['foo']['baz'] = True
print(my_dict)

dict creates a new dictionary object. dict创建一个新字典 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM