Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge list by dictionary key and sum values if key is same

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 idvalue 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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading