在一个键上加入两个词典列表

时间:2011-03-31 14:53:36

标签: python

鉴于n列表中包含m字典作为其元素,我想生成一个新列表,其中包含一组连接的字典。每个字典都保证有一个名为“索引”的键,但除此之外可以有一组任意键。非索引键永远不会在列表中重叠。例如,想象以下两个列表:

l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}]
l2 = [{"index":1, "c":4}, {"index":2, "c":5}]

"b"永远不会出现在l2中,因为它出现在l1中,类似地,"c"永远不会出现在l1中,因为它出现了在l2

我想制作一个联合名单:

l3 = [{"index":1, "b":2, "c":4}, 
      {"index":2, "b":3, "c":5}, 
      {"index":3, "green":"eggs"}]

在Python中执行此操作的最有效方法是什么?

3 个答案:

答案 0 :(得分:34)

from collections import defaultdict

l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}]
l2 = [{"index":1, "c":4}, {"index":2, "c":5}]

d = defaultdict(dict)
for l in (l1, l2):
    for elem in l:
        d[elem['index']].update(elem)
l3 = d.values()

# l3 is now:

[{'b': 2, 'c': 4, 'index': 1},
 {'b': 3, 'c': 5, 'index': 2},
 {'green': 'eggs', 'index': 3}]

编辑:由于l3无法保证排序(.values()按特定顺序返回商品),您可以按@ user560833建议:

from operator import itemgetter

...

l3 = sorted(d.values(), key=itemgetter("index"))

答案 1 :(得分:0)

这是一个单行代码:

[dict(sum([z.items() for z in z2],[])) for z2 in [[x3 for x3 in l1+l2 if x3['index']==key] for key in set([x1['index'] for x1 in l1]+[x2['index'] for x2 in l2])]]

不像列表理解那么优雅。我认为结果不一定按照你想要的方式排序。

扩展单行:

[
    dict(sum([z.items() for z in z2],[])) 
    for z2 in [
        [
            x3 for x3 in l1+l2 if x3['index']==key
        ] for key in set(
            [x1['index'] for x1 in l1]+[x2['index'] for x2 in l2]
        )
    ]
]

第6行的set表达式获取两个列表中的所有唯一索引值。围绕该列表理解(第3-9行)创建列表列表,其中每个内部列表是具有特定索引值的该索引/键的字典的组合列表。最外层列表理解为每个键创建一个元组对列表,并将其转换回字典列表。

答案 2 :(得分:0)

在python 3.5或更高版本中,您可以merge dictionaries in a single statement

因此对于python 3.5或更高版本,一个快速的解决方案是:

from itertools import zip_longest

l3 = [{**u, **v} for u, v in zip_longest(l1, l2, fillvalue={})]

print(l3)
#[
#    {'index': 1, 'b': 2, 'c': 4}, 
#    {'index': 2, 'b': 3, 'c': 5}, 
#    {'index': 3, 'green': 'eggs'}
#]

但是,如果两个列表的大小相同,则只需使用zip:

l3 = [{**u, **v} for u, v in zip(l1, l2)]

注意:这假设列表是通过index(即stated by OP to not be the case in general)以相同的方式排序的。

为了对此进行一般化,一种方法是创建一个自定义的zip-longest类型的函数,该函数仅在两个列表上的键匹配时才从两个列表中产生值。

例如:

def sortedZipLongest(l1, l2, key, fillvalue={}):  
    l1 = iter(sorted(l1, key=lambda x: x[key]))
    l2 = iter(sorted(l2, key=lambda x: x[key]))
    u = next(l1, None)
    v = next(l2, None)

    while (u is not None) or (v is not None):  
        if u is None:
            yield fillvalue, v
            v = next(l2, None)
        elif v is None:
            yield u, fillvalue
            u = next(l1, None)
        elif u.get(key) == v.get(key):
            yield u, v
            u = next(l1, None)
            v = next(l2, None)
        elif u.get(key) < v.get(key):
            yield u, fillvalue
            u = next(l1, None)
        else:
            yield fillvalue, v
            v = next(l2, None)

现在,如果您有以下乱序列表:

l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}, 
      {"index":4, "b": 4}]
l2 = [{"index":1, "c":4}, {"index":2, "c":5}, {"index":0, "green": "ham"}, 
      {"index":4, "green": "ham"}]

使用sortedZipLongest函数代替itertools.zip_longest

l3 = [{**u, **v} for u, v in sortedZipLongest(l1, l2, key="index", fillvalue={})]
print(l3)
#[{'index': 0, 'green': 'ham'},
# {'index': 1, 'b': 2, 'c': 4},
# {'index': 2, 'b': 3, 'c': 5},
# {'index': 3, 'green': 'eggs'},
# {'index': 4, 'b': 4, 'green': 'ham'}]

原始方法会产生错误的答案:

l3 = [{**u, **v} for u, v in zip_longest(l1, l2, fillvalue={})]
print(l3)
#[{'index': 1, 'b': 2, 'c': 4},
# {'index': 2, 'b': 3, 'c': 5},
# {'index': 0, 'green': 'ham'},
# {'index': 4, 'b': 4, 'green': 'ham'}]