比较两个词典列表和更新列表与缺少键值对

时间:2016-12-20 05:41:51

标签: python python-2.7 list dictionary

我有两个列表词典'

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的值进行比较。

最终结果如下:

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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

享受:

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'}]