ChikChak
ChikChak

Reputation: 1034

List of dictionaries with same structure into single dictionary under single key

I have a list of dictionaries which all of them have the same structure(example list):

[{ 'unique_name1':{ inner_dict1}}, { 'unique_name2':{ inner_dict2}}]

And I want to output a single dict, of the following structure:

{'general key':{ 'unique_name1': {inner_dict1}, 'unique_name2': {inner_dict2}}

Is there any one-liner/Python library that could do it for me?

Upvotes: 0

Views: 91

Answers (2)

IoaTzimas
IoaTzimas

Reputation: 10624

Here is my suggestion:

l=[{'unique_name_1':{'a':10, 'b':20}}, {'unique_name_2':{'a':100, 'b':200}}]

d={'general_key':{list(i.keys())[0]:list(i.values())[0] for i in l}}

>>> print(d)
{'general_key': {'unique_name_1': {'a': 10, 'b': 20}, 'unique_name_2': {'a': 100, 'b': 200}}}

Upvotes: 0

Dr. Prof. Patrick
Dr. Prof. Patrick

Reputation: 1374

Maybe try this:

result_dict = {

      'general_key': {k: v for d in dict_list for k, v in d.items()}         

}

So basically for each dict in your list you are creating a key-value pair in your new dict. The key being the unique_key and the value is the dict that is contained in the original dict.

Upvotes: 3

Related Questions