Home > Software engineering >  how to get the list value from list of dict
how to get the list value from list of dict

Time:10-27

Let's say I have one list below, which consist of dictionary. I wanted to get the key with list of combined value for same key.

abc=[{'sub':'1','id':'1'},{'sub':'1','id':'2'},{'sub':'2','id':'3'}]

exxpected output:

[{'sub':1,'id':[1,2]},{'sub':2,id:[3]}]

CodePudding user response:

Kindly let me know if this what you were anticipating.

result = (pd.DataFrame(abc).groupby(['sub'])
       .agg(list)
       .reset_index()
       .to_dict('r'))

Output:

[{'sub': '1', 'id': ['1', '2']}, {'sub': '2', 'id': ['3']}]
  • Related