1

I have 2 lists of dictionaries:

dict1 = [{"a":1, "b":2, "c":1295}, {"a":2, "b":5, "c":6274}, {"a":3, "b":1, "c":5337}]

and

dict2 = `[{"a":1, "b":2, "d":1884}, {"a":2, "b":5, "d":2049}, {"a":3, "b":3, "d":1086}]

The first list of dicts has the keys "a", "b" and "c", while the second list has keys "a", "b" and "d".

I want to create a list of merged dicts having all 4 keys. Only the dicts with equal values for "a" and "b" need to be merged.

The expected result looks like this:

[{"a":1, "b":2, "c":1295, "d":1884}, {"a":2, "b":5, "c":6274, "d":2049}]

I am looking for a Pythonic way of doing this.

timgeb
  • 76,762
  • 20
  • 123
  • 145
Tuhin Sah
  • 235
  • 1
  • 3
  • 8

1 Answers1

4

Assuming the merging-candidates from the two lists are the dicts from the same position, you can zip your lists together, employ a list comprehension and use the **-syntax idiom for merging two dicts.

>>> dicts1 = [{"a":1, "b":2, "c":1295}, {"a":2, "b":5, "c":6274}, {"a":3, "b":1, "c":5337}]
>>> dicts2 = [{"a":1, "b":2, "d":1884}, {"a":2, "b":5, "d":2049}, {"a":3, "b":3, "d":1086}]
>>> 
>>> [{**d1, **d2} for d1, d2 in zip(dicts1, dicts2) if all(d1[k] == d2[k] for k in ('a', 'b'))]
[{'a': 1, 'b': 2, 'c': 1295, 'd': 1884},
 {'a': 2, 'b': 5, 'c': 6274, 'd': 2049}]

Bonus pandas solution:

>>> df1 = pd.DataFrame(dicts1)
>>> df2 = pd.DataFrame(dicts2)
>>> 
>>> df1
   a  b     c
0  1  2  1295
1  2  5  6274
2  3  1  5337
>>> 
>>> df2
   a  b     d
0  1  2  1884
1  2  5  2049
2  3  3  1086
>>> 
>>> pd.merge(df1, df2, on=['a', 'b']).to_dict(orient='records')
[{'a': 1, 'b': 2, 'c': 1295, 'd': 1884},
 {'a': 2, 'b': 5, 'c': 6274, 'd': 2049}]
timgeb
  • 76,762
  • 20
  • 123
  • 145