围绕一个非唯一键加入两个字典列表

时间:2011-11-30 19:00:07

标签: python

我有两个词典列表,比如说:

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"}]

我正在寻找一种优雅的方法,从l2取出钥匙并将它们放入l1。这是为了加入使用不同值作为索引的词典列表

该函数应该看起来像join(l1,l2,'customer'),并生成

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应该为l1中的每个字典都有一个字典。

如果l1和l2具有相同的非连接键且值不同,则l2优先。

l2将具有连接键的唯一值。

现在我尝试了这段丑陋的代码:

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

以及the solution from this SO question但是假设所有列表中只有一个索引。

谢谢

2 个答案:

答案 0 :(得分:3)

易:

SELECT *
FROM l1, l2
WHERE l1.customer = l2.customer

......开个玩笑......

def join(t1,t2,column):
    result = []
    for entry in t2:
        for match in [d for d in t1 if d[column] == entry[column]]:
            result.append(dict((k,v) for k,v in entry.items()+match.items()))
    return result

答案 1 :(得分:1)

替代答案......

def diff(d1, d2, key):
    if d1[key] != d2[key]:
        return d1
    new_keys = list(set(d2) - set(d1))
    for new_key in new_keys:
        d1[new_key] = d2[new_key]
    return d1

def join(l1, l2, key):
    l3 = l1
    for d2 in l2:
        l3 = map(lambda d1: diff(d1, d2, key), l3)
    return l3