Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of dictionaries to a dictionary

I have a list of dictionaries in Python

[
{'id':'1', 'name': 'a', 'year': '1990'},
{'id':'2', 'name': 'b', 'year': '1991'},
{'id':'3', 'name': 'c', 'year': '1992'},
{'id':'4', 'name': 'd', 'year': '1993'},
]

I want to turn this list into a dictionary of dictionaries with the key being the value of name. Note here different items in the list have different values of name.

{
'a': {'id':'1', 'year': '1990'},
'b': {'id':'2', 'year': '1990'},
'c': {'id':'3', 'year': '1990'},
'd': {'id':'4', 'year': '1990'}
}

What is the best way to achieve this? Thanks.

This is similar to Python - create dictionary from list of dictionaries, but different.

like image 422
Tim Avatar asked Dec 02 '22 14:12

Tim


2 Answers

You can also achieve this using Dictionary Comprehension.

data = [
        {'id':'1', 'name': 'a', 'year': '1990'},
        {'id':'2', 'name': 'b', 'year': '1991'},
        {'id':'3', 'name': 'c', 'year': '1992'},
        {'id':'4', 'name': 'd', 'year': '1993'},
       ]

print {each.pop('name'): each for each in data}  

Results :-

{'a': {'year': '1990', 'id': '1'}, 
 'c': {'year': '1992', 'id': '3'}, 
 'b': {'year': '1991', 'id': '2'}, 
 'd': {'year': '1993', 'id': '4'}}
like image 185
Tanveer Alam Avatar answered Dec 06 '22 09:12

Tanveer Alam


def to_dict(dicts):
    if not dicts:
        return {}
    out_dict = {}
    for d in dicts:
        out_dict[d.pop('name')] = d
    return out_dict
like image 38
Łukasz Rogalski Avatar answered Dec 06 '22 10:12

Łukasz Rogalski