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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With