简体   繁体   中英

How to append a list of dictionaries to the value of a key in a dictionary?

For example:

list1 = [{'vehicle': {'bmw': 2, 'cus': 'mr x', 'extra': 'he is awesome'}}, 
        {'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}]

print(list1)

[{'vehicle': {'bmw': 2, 'cus': 'mr x', 'extra': 'he is awesome'}},
{'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}]

final_ds_dict={}

final_ds_dict.update({'datasets': {'training': list1}})

print(final_ds_dict)

The output I am getting is as follows:

{'datasets': {'training': [{'vehicle': {'bmw': 2,
     'cus': 'mr x',
     'extra': 'he is awesome'}},
   {'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}]}}

However, I don't to append it as list.

The Desired output should be as follows:

{'datasets': {'training': {'vehicle': {'bmw': 2,
     'cus': 'mr x',
     'extra': 'he is awesome'}},
   {'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}}}

Can someone please help resolve this?

You can use a list comprehension with dict to form the inner dictionary:

list1 = [{'vehicle': {'bmw': 2, 'cus': 'mr x', 'extra': 'he is awesome'}}, 
    {'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}]
result = {'datasets':dict(i for b in list1 for i in b.items())}

Output:

{'datasets': 
    {'vehicle': {'bmw': 2, 'cus': 'mr x', 'extra': 'he is awesome'}, 
     'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}
    }
}

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