Faizalprbw
Faizalprbw

Reputation: 529

How to combine two list containing dictionary with similar keys?

Assuming that there are two python list with the same structure like this:

var1 = [{'a':1,'b':2},{'c':2,'d':5,'h':4},{'c':2,'d':5,'e':4}]
var2 = [{'a':3,'b':2},{'c':1,'d':5,'h':4},{'c':5,'d':5,'e':4}]

In my case, i need to combine both of those list, so i'll get this value :

result = [{'a':4,'b':4},{'c':3,'d':10,'h':8},{'c':7,'d':10,'e':8}]

How can i do that?

Upvotes: 3

Views: 419

Answers (6)

The Stupid Engineer
The Stupid Engineer

Reputation: 402

Would something like this help?

ar1 = [{'a':1,'b':2},{'c':2,'d':5,'h':4},{'c':2,'d':5,'e':4}]
var2 = [{'a':3,'b':2},{'c':1,'d':5,'h':4},{'c':5,'d':5,'e':4}]

combined_var = zip(var1, var2)

new_d = {}
list_new_ds = []

for i, j in combined_var:
    new_d = {}
    for key in i and j:
        new_d[key] = i[key] + j[key]
    list_new_ds.append(new_d)

list_new_ds = [{'a': 4, 'b': 4}, {'h': 8, 'c': 3, 'd': 10}, {'c': 7, 'e': 8, 'd': 10}]

To explain, the zip function merges the lists as a list of tuples. I then unpack the tuples and iterate through the keys in each dictionary and add the values for the same keys together using a new dictionary to store them. I then append the value to a list, and then re-initialise the temporary dictionary to empty before looking at the next tuple in the zipped list.

The order is different due to dictionary behaviour I believe.

I am a novice, so would appreciate any critiques of my answer!

Upvotes: 0

SparkAndShine
SparkAndShine

Reputation: 18007

Use list comprehensions to put the code in one line,

result = [{key : d1.get(key, 0)+d2.get(key, 0) 
            for key in set(d1.keys()) | set(d2.keys())}     # union two sets
            for d1, d2 in zip(var1, var2)]

print(result)
[{'a': 4, 'b': 4}, {'h': 8, 'c': 3, 'd': 10}, {'c': 7, 'e': 8, 'd': 10}]

This code takes into consideration the case that two dictionaries may not have the same keys.

Upvotes: 2

user2390182
user2390182

Reputation: 73450

zip-based one-liner comprehension:

result = [{k: d1[k]+d2[k] for k in d1} for d1, d2 in zip(var1, var2)]

This assumes that two dicts at the same index always have identical key sets.

Upvotes: 5

zwer
zwer

Reputation: 25779

For the sake of completeness, another zip-based one-liner that will work even if the dicts are uneven in the both lists:

result = [{k: d1.get(k, 0) + d2.get(k, 0) for k in set(d1) | set(d2)} for d1, d2 in zip(var1, var2)]

Upvotes: 0

ac2001
ac2001

Reputation: 736

var1 = [{'a': 1, 'b': 2}, {'c': 2, 'd': 5, 'h': 4}, {'c': 2, 'd': 5, 'e': 4}]
var2 = [{'a': 3, 'b': 2}, {'c': 1, 'd': 5, 'h': 4}, {'c': 5, 'd': 5, 'e': 4}]

ret = []

for i, ele in enumerate(var1):
    d = {}
    for k, v in ele.items():
        value = v
        value += var2[i][k]
        d[k] = value
    ret.append(d)

print(ret)

Upvotes: 0

akasolace
akasolace

Reputation: 624

var1 = [{'a':1,'b':2},{'c':2,'d':5,'h':4},{'c':2,'d':5,'e':4}]
var2 = [{'a':3,'b':2},{'c':1,'d':5,'h':4},{'c':5,'d':5,'e':4}]

res = []
for i in range(len(var1)):
    dic = {}
    dic1, dic2 = var1[i], var2[i]
    for key, val in dic1.items():  // dic1.iteritems() in python 2.
        dic[key] = dic1[key] + dic2[key]
    res.append(dic)

>>>print(res)
[{'a': 4, 'b': 4}, {'c': 3, 'd': 10, 'h': 8}, {'c': 7, 'd': 10, 'e': 8}]

Upvotes: 0

Related Questions