简体   繁体   English

我如何将字典 append 作为现有字典键的另一个值

[英]How do I append a dictionary as another value to an existing dictionary key

I currently have a nested dictionary, with a dictionary as a value我目前有一个嵌套字典,以字典为值

I want to add another dictionary as SECOND item to the same key so that it looks something like this:我想将另一个字典作为 SECOND 项添加到同一个键,使其看起来像这样:

{'mykey1': {'-11111': 0, 'A': 1}, {Second dictionary}, ...}

"append" doesn't work and "update" replaces the value. “追加”不起作用,“更新”替换了该值。

Do I need something like a list of dictionaries for the value?我需要像字典列表这样的值吗?

{'mykey1': [{'-11111': 0, 'A': 1}, {'-11111': 201910, 'A': 201910}] ,
 'mykey2': [{'-11111': 0, 'A': 1}, {'-11111': 201909, 'A': 201910}]}

In which case: a) How do I append the second dictionary element to each key in the existing dict?在这种情况下:a)我如何 append 现有字典中每个键的第二个字典元素? b) How do I access that second dictionary? b)我如何访问第二个字典? thanks谢谢

Yes you need a list or a tuple for your Task.是的,您的任务需要一个列表或一个元组。 try to store the two dictionaries in a list and then assign it to the wrapper dictionary尝试将两个字典存储在一个列表中,然后将其分配给包装字典

ls = [{'-11111': 0, 'A': 1},{'-11111': 201910, 'A': 201910} ]

dic = {}
dic["myKey1"] = ls

or simply:或者简单地说:

ls = [{'-11111': 0, 'A': 1},{'-11111': 201910, 'A': 201910} ]

dic = {"mykey": ls}
print(dic)  # {'mykey': [{'-11111': 0, 'A': 1}, {'-11111': 201910, 'A': 201910}]} 

you just need to build each object in turn.您只需要依次构建每个 object。

first_dict{key}.update(list(first_dict{key}, {second_dict}.

will take the existing value from the dictionary for a given key and replace it with a list of that value plus another dictionary, second_dict将从字典中获取给定键的现有值,并将其替换为该值的列表加上另一个字典second_dict

It isn't totally clear to me what how you want to structure your data.我并不完全清楚你想如何构建你的数据。

If you built a little example of exactly what you want the data to be structured as, it'll be easier to give an exact answer.如果您构建了一个小示例,说明您希望数据的结构是什么,那么给出准确的答案会更容易。

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

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