Given n
lists with m
dictionaries as their elements, I would like to produce a new list, with a joined (left join) set of dictionaries. Each dictionary is guaranteed to have a key called index
, but could have an arbitrary set of keys beyond that. For example, imagine the following two lists:
l1 = [{"index":1, "b":2},
{"index":2, "b":3},
{"index":3, "b":"10"},
{"index":4, "c":"7"}]
l2 = [{"index":1, "c":4},
{"index":2, "c":5},
{"index":6, "c":8},
{"index":7, "c":9}]
I would like to produce a joined list:
l3 = [{"index":1, "b":2, "c":4},
{"index":2, "b":3, "c":5},
{"index":3, "b":10},
{"index":4, "c":7}]
What is the most efficient way to do this in Python?
Currently I have this piece of code, but it only does an inner join, how can I modify this to give me a left join?
def left_join(left, right, key):
merged = {}
for item in left+right:
if item[key] in merged:
merged[item[key]].update(item)
else:
merged[item[key]] = item
return [val for (_, val) in merged.items()]