[英]How to append multiple key and value into a nested dictionary using python?
I have looked through few questions regarding nested dictionary such as link_a , link_b , and link_c .我浏览了一些关于嵌套字典的问题,例如link_a 、 link_b和link_c 。 But i cant seem to find the solution (or i couldnt figure it out).
但我似乎无法找到解决方案(或者我无法弄清楚)。 So i already have a dictionary which is in this format:
{'key_01': ['value1', 'value2'], key_02: ....}
which goes until key_08 where certain keys have different amount of 'value' in them.所以我已经有一个这种格式的字典:
{'key_01': ['value1', 'value2'], key_02: ....}
直到 key_08 某些键在其中具有不同数量的“值” .
For each value1 and value2 has 2 more additional values which are x
and y
in which i will obtain once i run my program.对于每个 value1 和 value2,还有 2 个额外的值,它们是
x
和y
,一旦我运行我的程序,我将获得它们。
So the final output that i want it as below:所以我想要的最终输出如下:
{'key_01':
['value1' :
['x': 2],
['y': 3]],
['value2':
['x': 2],
['y': 3]], ....}
This is one of the method i tried by using this tutorial for adding into dictionary:这是我尝试使用本教程添加到字典中的方法之一:
x = 5
for i in range(len(demo_dict['key_01'])):
for val in demo_dict['key_01']:
demo_dict['key_01'][0] = x
But it changed the value1 to 5 which is not what i want.但它将 value1 更改为 5,这不是我想要的。 And i know i cannot use append.
而且我知道我不能使用附加。 Now im stuck.
现在我卡住了。
I believe you need我相信你需要
data = {'key_01': ['value1', 'value2'], key_02: ....}
result = {}
for k, v in data.items():
for i in v:
result.setdefault(k, {}).update({'v': {'x': x, 'y': y}})
Output:输出:
{'key_01': {
'v': {
'x': x,
'y': y
}
}
}
every pair of 'key':value should be in a dictionary, like:每对 'key':value 都应该在字典中,例如:
dict = {'key_01':[
{'value1':{'x': 2,'y': 3},
'value2':{'x': 2,'y': 3},
'value3': ....]}
So key_01 has a list of dictionaries value1,value2,value3, where each has a dictionary for x and y.所以key_01 有一个字典value1、value2、value3 的列表,其中每个字典都有一个x 和y 的字典。
this way you can access the 'x' and 'y' values as这样您就可以访问“x”和“y”值作为
dict['value_01']['value1']['x'] and dict['value_01']['value1']['x']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.