Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary list merging

I want to join the dictionaries in a list whose key 'user' are the same, but I don't realize how. for example:

[{'count2': 34, 'user': 2},
 {'count4': 233, 'user': 2},
 {'count2': 234, 'user': 4},
 {'count4': 344, 'user': 5}]

would become:

[{'count2': 34, 'count4': 233, 'user': 2 },
 {'count2': 234, 'user': 4},
 {'count4': 344, 'user': 5}]

I searched extensively without found something similar in stack overflow, any help would be greatly appreciated.

like image 344
Arkantos Avatar asked Aug 09 '26 19:08

Arkantos


1 Answers

from collections import defaultdict

dl = [{'count2': 34, 'user': 2},
{'count4': 233, 'user': 2},
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
print dl

dd = defaultdict(dict)
for d in dl:
    dd[d['user']].update(d)
print dd.values()
like image 58
dugres Avatar answered Aug 12 '26 11:08

dugres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!