合并具有不同键的两个字典列表

时间:2020-04-11 03:07:47

标签: python python-3.x dictionary

我有两个字典清单。

list1 = [{'id': '1', 'name': 'one'},{'id': '2', 'name': 'two'}]
list2 = [{'age': '52', 'sal': '95'}, {'age': '37', 'sal': '86'}]

我想合并这些列表以获得以下列表:

list3 = [{'id': '1', 'name': 'one', 'age': '52', 'sal': '95'},{'id': '2', 'name': 'two', 'age': '37', 'sal': '86'}]

list1.extend(list2) hasn't given me the desired result.

3 个答案:

答案 0 :(得分:2)

字典和update的可变性给出了所需的答案,但存储在list1中。

[lst1.update(lst2) for lst1, lst2 in zip(list1, list2)]
print(list1)

答案 1 :(得分:1)

您可以使用dict.update()函数在调用它的对象中合并2个字典对象:

a = {'id': '1', 'name': 'one'}
b = {'age': '52', 'sal': '95'}
a.update(b)
print(a) # {'id': '1', 'name': 'one', 'age': '52', 'sal': '95'}

由于您需要对2个列表中相同索引处的每两个对应的字典元素执行此操作:

def mergeDictLists(list1, list2):
    result = [] 
    for i in range(len(list1)):
        a = list1[i].copy() # so that list1 elements are not modified by a shallow copy
        b = list2[i]
        a.update(b)
        result.append(a)
    return result

list1 = [{'id': '1', 'name': 'one'},{'id': '2', 'name': 'two'}]
list2 = [{'age': '52', 'sal': '95'}, {'age': '37', 'sal': '86'}]
list3 = mergeDictLists(list1, list2)
print(list3) # [{'id': '1', 'name': 'one', 'age': '52', 'sal': '95'}, {'id': '2', 'name': 'two', 'age': '37', 'sal': '86'}]

答案 2 :(得分:0)

您可以zip合并两个列表,并将两个词典与{**x, **y}合并:

list3 = [{**x, **y} for x, y in zip(list1, list2)]