Home > other >  Program in python where input: [{'a':5,'b':7},{'a':3,'b':5}]
Program in python where input: [{'a':5,'b':7},{'a':3,'b':5}]

Time:10-23

Program in python where input: [{'a':5,'b':7},{'a':3,'b':5}] Output:{'a':[5,3],'b':[7,5]} The code should be dynamic. I tried but i am unable to approach if anyone has some idea on this please share.

CodePudding user response:

You can use setdefault as list like below:

>>> lst = [{'a':5,'b':7},{'a':3,'b':5}]

>>> dct = {}
>>> for l in lst:
...    for k,v in l.items():
...        dct.setdefault(k, []).append(v)
>>> dct
{'a': [5, 3], 'b': [7, 5]}

CodePudding user response:

This is a classical use case for collections.defaultdict:

from collections import defaultdict

l = [{'a':5,'b':7},{'a':3,'b':5}] 

out = defaultdict(list)
for d in l:
    for k,v in d.items():
        out[k].append(v)

output:

>>> dict(out)
{'a': [5, 3], 'b': [7, 5]}
  • Related