3

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?

akshat
  • 1,219
  • 1
  • 8
  • 24

2 Answers2

11

The dict comprehension, even though not impossible, might not be the best choice. May I suggest using a defaultdict:

from collections import defaultdict

dic = defaultdict(list)
for i in data:
    dic[i['Dept']].append(i['Name'])
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
5

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}
}
Underyx
  • 1,599
  • 1
  • 17
  • 23
  • 2
    I don't consider it too complicated at all. However, it's slower in a big-O sense, because the data has to be re-scanned once for each unique key found - worst-case O(N^2). – Karl Knechtel Apr 16 '15 at 16:08