比较两个字典列表,并更新缺少键值对的列表 [英] compare two list of dictionaries and update list with missing key value pair

查看:112
本文介绍了比较两个字典列表,并更新缺少键值对的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表字典.

L1 =  [{'y': 3L, 'x': u'2016-10'}, {'y': 3L, 'x': u'2016-12'}]
L2 = [{'y': 0, 'x': '2016-12'}, {'y': 0, 'x': '2016-11'}, {'y': 0, 'x': '2016-10'}]

将这两个列表的值与x进行比较.

Compare these two list with value of x.

最终结果如下:

output= [{'y': 3L, 'x': '2016-12'}, {'y': 0, 'x': '2016-11'}, {'y': 3L, 'x': '2016-10'}]

我该怎么办?

推荐答案

享受:

L1 =  [{'y': 3L, 'x': u'2016-10'}, {'y': 3L, 'x': u'2016-12'}]
L2 = [{'y': 0, 'x': '2016-12'}, {'y': 0, 'x': '2016-11'}, {'y': 0, 'x': '2016-10'}]

output = []
for e2 in L2:
    found = False
    for e1 in L1:
        if e1['x'] == e2['x']:
            output.append(e1)
            found = True
            break
    if not found:
        output.append(e2)

print output # output= [{'y': 3L, 'x': '2016-12'}, {'y': 0, 'x': '2016-11'}, {'y': 3L, 'x': '2016-10'}]

这篇关于比较两个字典列表,并更新缺少键值对的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆