简体   繁体   English

如何正确更新 Python 嵌套字典中列表类型的值?

[英]How to correctly update the values of list types in a Python nested dictionary?

The case is that I'd like to build a nested dictionary with the structure like the following情况是我想构建一个嵌套字典,其结构如下

{'a': {'1': [], '2': [], '3': [], '4': []},
 'b': {'1': [], '2': [], '3': [], '4': []},
 'c': {'1': [], '2': [], '3': [], '4': []}}

and the initiation part is启动部分是

keys = ['a','b','c']
subkeys = ['1','2','3','4']
target_dict = dict.fromkeys(keys, {key: [] for key in subkeys})

and then, I want to update the values of a subkey, like target_dict['a']['1'] = 1 , which i only want to set the entry "a-1" to 1, and leave other values blank.然后,我想更新一个子键的值,比如target_dict['a']['1'] = 1 ,我只想将条目“a-1”设置为 1,并将其他值留空。 However, the "a-1", "b-1", and "c-1" all update simultaneously.但是,“a-1”、“b-1”和“c-1”都同时更新。 Leading to the result as导致结果为

{'a': {'1': 1, '2': [], '3': [], '4': []},
 'b': {'1': 1, '2': [], '3': [], '4': []},
 'c': {'1': 1, '2': [], '3': [], '4': []}}

what's the reason of this case, and how should I fix it?这种情况的原因是什么,我应该如何解决? Thanks.谢谢。

The problem is that target_dict['a'] target_dict['b'] and target_dict['c'] seems to be keeping the same reference.问题是target_dict['a'] target_dict['b']target_dict['c']似乎保持相同的引用。 Try changing your code to尝试将您的代码更改为

target_dict = {k: {key: [] for key in subkeys} for k in keys}

You're giving each key the same object (a dict) as a value.您为每个键提供了相同的对象(字典)作为值。 Regardless of which key you use to access the dict and modify it, there's only one dict, so it's reflected for all the other keys.无论您使用哪个键来访问 dict 并对其进行修改,都只有一个 dict,因此它会反映所有其他键。

Creating a dict for each key solves the problem:为每个键创建一个 dict 解决了这个问题:

>>> keys = ['a','b','c']
>>> subkeys = ['1','2','3','4']
>>> target_dict = {key: {subkey: [] for subkey in subkeys} for key in keys}
>>> target_dict
{'a': {'1': [], '2': [], '3': [], '4': []}, 'b': {'1': [], '2': [], '3': [], '4': []}, 'c': {'1': [], '2': [], '3': [], '4': []}}
>>> target_dict['a']['1'].append(1)
>>> target_dict
{'a': {'1': [1], '2': [], '3': [], '4': []}, 'b': {'1': [], '2': [], '3': [], '4': []}, 'c': {'1': [], '2': [], '3': [], '4': []}}
keys = ['a','b','c']
subkeys = ['1','2','3','4']

temp = lambda x: dict(zip(subkeys, [[1] if x == "a" and i == 0 else [] for i in range(len(subkeys))]))
target_dict = {k:v for k, v in zip(keys, [temp(key) for key in keys])}
print(target_dict)
# {'a': {'1': [1], '2': [], '3': [], '4': []}, 'b': {'1': [], '2': [], '3': [], '4': []}, 'c': {'1': [], '2': [], '3': [], '4': []}}

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

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