如何基于值合并两个字典列表

时间:2020-09-12 18:25:33

标签: python dictionary

我有两个字典列表,可以这样说:

a = [{'id': 1, 'name': 'a'}]
b = [{'id': 1, 'city': 'b'}]

我想要一个列表,将两个列表中的每个字典合并为相同的ID。在此示例中,我希望具有:

a = [{'id': 1, 'name': 'a', 'city': 'b'}]

除了将for嵌套到另一个之外,还有其他更清洁的方法吗?

谢谢

3 个答案:

答案 0 :(得分:3)

您可以使用另一个字典(或默认字典来简化操作)来跟踪ID。然后在迭代时更新该字典中的项目。最后,字典的值将包含在您的列表中。

from collections import defaultdict
d = defaultdict(dict)

a = [{'id': 1, 'name': 'a'}, {'id': 3, 'name': 'a'}]
b = [{'id': 1, 'city': 'b'}, {'id': 2, 'city': 'c'}, {'id': 3, 'city': 'd'}]

for item in a + b:
    d[item['id']].update(item)
list(d.values())

# [{'id': 1, 'name': 'a', 'city': 'b'},
#  {'id': 3, 'name': 'a', 'city': 'd'},
#  {'id': 2, 'city': 'c'}]

请注意,这将覆盖id以外的重复值-因此,如果您有两个id: 1和两个不同的城市,则只会得到最后一个城市。

答案 1 :(得分:1)

一种方法是制作一个字典,将要使用的标识符(在这种情况下为id)映射到合并结果的字典。

@typeparam T : class
@typeparam T : IEnumerable
@typeparam T where T : struct
@typeparam T where T : IEnumerable

返回:

#!/usr/bin/python

import collections

def merge_on_key(list_of_dictionaries, key, result):
    for d in list_of_dictionaries:
        assert(key in d)
        result[d[key]].update(d)

a = [{'id': 1, 'name': 'a'}]
b = [{'id': 1, 'city': 'b'}, {'id': 2, 'color': 'blue'}]

print 'a', a
print 'b', b

c = collections.defaultdict(lambda: {})
merge_on_key(a, 'id', c)
merge_on_key(b, 'id', c)

print 'merged results in dictionary with id 1', c[1]

答案 2 :(得分:1)

对于字典,您可以将maplambda函数与update方法结合使用,例如:

a = [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'a'}, {'id': 3, 'name': 'k'}]
b = [{'id': 1, 'city': 'b'}, {'id': 2, 'city': 'c'},  {'id': 4, 'city': 'cm'}]
a.extend(list(map(lambda x,y: y if x.get('id') != y.get('id') else x.update(y), a, b)))
a = list(filter(None, a))

a现在将成为一个包含合并值字典的列表,如下所示:

[{'id': 1, 'name': 'a', 'city': 'b'},
 {'id': 2, 'name': 'a', 'city': 'c'},
 {'id': 3, 'name': 'k'},
 {'id': 4, 'city': 'cm'}]