I have a list of dictionary like this:
# sample data
data = [
[
{'id': '1', 'value': '10'},
{'id': '2', 'value': '5'},
{'id': '3', 'value': '15'},
{'id': '4', 'value': '20'},
# ... many
],
[
{'id': '2', 'value': '5'},
{'id': '3', 'value': '5'},
# ... many
],
[
{'id': '4', 'value': '10'},
# ... many
],
# ... many
]
Now I want to loop through all data, and add values if the id is same, and merge back to single list.
# sample output
[
{'id': '1', 'value': '10'}, # there is no id 1 in other array so the value remain same
{'id': '2', 'value': '10'}, # same id found in another array so add value
{'id': '3', 'value': '20'}, # same id found in another array so add value
{'id': '4', 'value': '30'}, # same id found in another array so add value
]
How can I achieve that?
This is what I’ve done so far:
def merge(data):
master_list = []
for i in data:
thislist = []
find = [item.get('id') for item in i]
for j in i:
j_id = j.get('id')
if j_id in find:
# add some logic here..
thislist.append(j)
else:
thislist.append(j)
# add some logic here..
master_list.append(thislist)
return master_list
print(merge(data))
>Solution :
You can use collections.Counter. First, iterate over data and create dictionaries from id–value pairs. Then cast these dictionaries to collections.Counter and add these counters.
Finally, unpack the counter back into a list of dictionaries.
from collections import Counter
count = Counter()
for lst in data:
for d in lst:
count += Counter({d['id']:int(d['value'])})
out = [dict(zip(('id','value'), map(str, pair))) for pair in count.items()]
Output:
[{'id': '1', 'value': '10'},
{'id': '2', 'value': '10'},
{'id': '3', 'value': '20'},
{'id': '4', 'value': '30'}]