简体   繁体   中英

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:

{'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? b) How do I access that second dictionary? 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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