I have 2 lists of dictionaries, say:
l1 = [{"customer":"amy", "order":2}, {"customer":"amy", "order":3}, {"customer":"basil", "order":4}]
l2 = [{"customer":"amy", "died":"who fell down the stairs"}, {"customer":'basil', "died":"assaulted by bears"}]
I am looking for an elegant way of taking the keys from l2 and putting them into l1. This is for joining lists of dictionaries that use different values as their index
The function should look something like join(l1,l2,'customer'), and produce
l3 = [{"customer":"amy", "order":2,"died":"who fell down the stairs"}, {"customer":"amy", "order":3,"died":"who fell down the stairs"}, {"customer":"basil", "order":4,"died":"assaulted by bears"}}]
l3 should have a dictionary for every dictionary in l1.
if l1 and l2 have the same non-joining key with different values, l2 takes, precedence.
l2 will have unique values for the joining key.
right now I have tried this ugly piece of code:
l3 = []
rdict = {}
for i in range(len(l2)):
rdict[l2[i][field]]=i
for d in l1:
l3.append(dict(d.items()+l2[rdict[d[field]]].items()))
return l3
as well as the solution from this SO question but that assumes only one index in all lists.
Thank you