How to join 2 dicts lists in python?

I have 2 lists:

l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] 

and I want to get a list l3 , which is the union of l1 and l2 , where the values โ€‹โ€‹of 'a' and 'b' are equal in both l1 and l2 that is.

 l3 = [{'a': 1, 'b: 2, 'c': 3, 'd': 4, 'e': 101}, {'a': 5, 'b: 6, 'c': 7, 'd': 8, 'e': 100}] 

How can i do this?

+5
source share
3 answers

You must accumulate results in a dictionary. You must use the values โ€‹โ€‹"a" and "b" to form the key of this dictionary

Here I used defaultdict to accumulate entries

 l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] from collections import defaultdict D = defaultdict(dict) for lst in l1, l2: for item in lst: key = item['a'], item['b'] D[key].update(item) l3 = D.values() print l3 

output:

 [{'a': 1, 'c': 3, 'b': 2, 'e': 101, 'd': 4}, {'a': 5, 'c': 7, 'b': 6, 'e': 100, 'd': 8}] 
+8
source

Simple list operations will also help you:

 l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] l3 = [] for i in range(len(l1)): for j in range(len(l2)): if l1[i]['a'] == l2[j]['a'] and l1[i]['b'] == l2[j]['b']: l3.append(dict(l1[i])) l3[i].update(l2[j]) 
+2
source

My approach is to sort the merged list using the key, which is the a + b keys. After that, for each group of dictionaries with a similar key, combine them:

 from itertools import groupby def ab_key(dic): return dic['a'], dic['b'] def combine_lists_of_dicts(list_of_dic1, list_of_dic2, keyfunc): for key, dic_of_same_key in groupby(sorted(list_of_dic1 + list_of_dic2, key=keyfunc), keyfunc): combined_dic = {} for dic in dic_of_same_key: combined_dic.update(dic) yield combined_dic l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] for dic in combine_lists_of_dicts(l1, l2, ab_key): print dic 

Discussion

  • The ab_key function returns a tuple of value for the key a and b , used to sort the grouping
  • The groupby function groups all dictionaries with similar keys together
  • This solution is less efficient than John La Rooy, but should work fine for small lists.
+1
source

All Articles