'How to add similar key value in python?
This is the array of data:
Input Data:
list1 = [{'user': 1, 'coins': 2}, {'user': 18, 'coins': 8}, {'user': 1, 'coins': 1}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}, {'user': 18, 'coins': 0}]
Expected Outcome:
list2 = [{'user': 1, 'coins': 3}, {'user': 18, 'coins': 8}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}]
So, there will be list1, and we have to add the coins to similar user which can be identified by user key value. If user key have similar value that is 1 (in above case) then coins of both or multiple user must be added making it a total sum of that user coins.
In above example, we can see that user with 1 as value in 2 different dict got added and total sum was given in list 2.
Solution 1:[1]
This can be easily done using a collections.defaultdict as intermediate data object:
import collections
dd = collections.defaultdict(int)
for d in list1:
dd[d['user']] += d['coins']
list2 = [{'user': user, 'coins': coins} for user, coins in dd.items()]
or similary, using a collections.Counter object:
cntr = collections.Counter()
for d in list1:
cntr[d['user']] += d['coins']
list2 = [{'user': user, 'coins': coins} for user, coins in cntr.items()]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wovano |
