比较并更新字典?

时间:2018-09-19 12:49:45

标签: python

我创建了两个词典列表

dict1 = [
    {'name':'Apple','lot':1234,'old_qty':100}, {'name':'Grape','lot':456,'old_qty':20}
] 

dict2 = [
    {'name':'Apple','lot':1234,'new_qty':50}, {'name':'Grape','lot':456,'new_qty':30}
] 

所需的输出:

[{'name':'Apple','lot':1234,'old_qty':100, 'new_qty':50}, {'name':'Grape','lot':456,'old_qty':20,'new_qty':30}]

我该怎么做?

4 个答案:

答案 0 :(得分:0)

也许您正在寻找这个:

result = [] 
for i,j in zip(dict1, dict2):
    i.update(j)
    result.append(i)

结果将是您想要的。

答案 1 :(得分:0)

假设您要合并两个共享一个名称的字典,请尝试以下操作:

dict1 = [{'name':'Apple','lot':1234,'old_qty':100},{'name':'Grape','lot':456,'old_qty':20}]
dict2 = [{'name':'Apple','lot':1234,'new_qty':50},{'name':'Grape','lot':456,'new_qty':30}]

z = []
common_attr = 'name'
for d1 in dict1:
    for d2 in dict2:
        if d1[common_attr] == d2[common_attr]:
            z.append({**d1, **d2})
print(z)

如果您打算使用其他逻辑进行合并,则此代码段可能仍会有所帮助。

希望这会有所帮助:)

答案 2 :(得分:0)

恕我直言,您正在寻找类似的东西(考虑键namelot的值可以唯一地识别其他字典):

dict1 = [{'name':'Apple','lot':1234,'old_qty':100},{'name':'Grape','lot':456,'old_qty':20}]
dict2 = [{'name':'Apple','lot':1234,'new_qty':50},{'name':'Grape','lot':456,'new_qty':30}]

dict3 = [d1 for d1 in dict1 for d2 in dict2 if d1["name"]==d2["name"] if d1["lot"]==d2["lot"] if not d1.update(d2)]

print(dict3)

答案 3 :(得分:0)

for循环只是一些分层

listc = lista[:] 

for i in listb:
    for j in listc:
        if i['name'] == j['name']:
            for x in i:
                if x not in j.keys():
                    j[x] = i[x]

print(listc)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 dicta_comp.py 
[{'name': 'Apple', 'lot': 1234, 'old_qty': 100, 'new_qty': 50}, {'name': 'Grape', 'lot': 456, 'old_qty': 20, 'new_qty': 30}]