Search code examples
pythonlistdictionarylist-comprehension

How to populate a dictionary of lists using comprehension?


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?


Solution

  • 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])