Home > Back-end >  How to populate a dictionary of lists using comprehension?
How to populate a dictionary of lists using comprehension?

Time:09-03

From this source list of dictionaries:

s = [ {'I':1}, {'I':2}, {'R':29}, {'R':33} ]

I want to create this dictionary, d:

{ 'I':[1,2], 'R':[29,33] }

And I can do it with what seems rather clumsy to me:

d = {'I':[], 'R':[]}
for i in s:
    for k,v in i.items():
        d[k].append(v)

It gets the job done, but I feel like I should be doing this with a comprehension of some sort. Right?

CodePudding user response:

d = {}
for k in ['I', 'R']:
    d[k] = [d_[k] for d_ in s if k in d_]

if you don't want to hardcode the list of keys to iterate over, you can determine them in advance, e.g. by replacing

['I', 'R']

with

set([list(d_.keys())[0] for d_ in s])

CodePudding user response:

Your approach looks fine to me. One way of doing it without knowing the keys present in s beforehand:

s = [ {'I':1}, {'I':2}, {'R':29}, {'R':33} ]

res = {}
for d in s:
    for k in d:
        res[k] = (res.get(k) or [])   [d[k]]

print(res)

Alternatively, this version might be a bit more efficient:

res[k] = res[k]   [d[k]] if k in res else [d[k]]

Output:

{'I': [1, 2], 'R': [29, 33]}
  • Related