Python Dict Comprehension to Create and Update Dictionary

akshat picture akshat · Apr 16, 2015 · Viewed 7.3k times · Source

I have a list of dictionaries (data) and want to convert it into dictionary (x) as below. I am using following ‘for loop’ to achieve.

data = [{'Dept': '0123', 'Name': 'Tom'},
        {'Dept': '0123', 'Name': 'Cheryl'},
        {'Dept': '0123', 'Name': 'Raj'},
        {'Dept': '0999', 'Name': 'Tina'}]
x = {}

for i in data:
    if i['Dept'] in x:
        x[i['Dept']].append(i['Name'])
    else:
        x[i['Dept']] = [i['Name']]

Output:
x -> {'0999': ['Tina'], '0123': ['Tom', 'Cheryl', 'Raj']}

Is it possible to implement the above logic in dict comprehension or any other more pythonic way?

Answer

Underyx picture Underyx · Apr 16, 2015

It seems way too complicated to be allowed into any code that matters even the least bit, but just for fun, here you go:

{
    dept: [item['Name'] for item in data if item['Dept'] == dept]
    for dept in {item['Dept'] for item in data}
}