Skip to content Skip to sidebar Skip to footer

Python Dict Comprehension To Create And Update Dictionary

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'},

Solution 1:

The dict comprehension, even though not impossible, might not be the best choice. May I suggest using defaultdict (https://docs.python.org/2/library/collections.html#collections.defaultdict):

from collections import defaultdict
dic = defaultdict(list)
for i in data:
    dic[i['Dept']].append(i['Name'])

Solution 2:

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}
}

Post a Comment for "Python Dict Comprehension To Create And Update Dictionary"