【问题标题】:compare two list of dictionaries and update list with missing key value pair比较两个字典列表和更新列表缺少键值对
【发布时间】:2017-05-05 06:33:54
【问题描述】:

我有两个列表字典'

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

我该怎么做?

【问题讨论】:

  • 虽然您可能在使用 Oddo 8,但您的问题不一定与它有关。请确保适当地标记:)
  • 恐怕我不确定你想要什么。您愿意编辑您的问题以提供更多详细信息吗?具体来说,您是如何得出示例中的输出的?
  • 如何比较?

标签: python python-2.7 list dictionary


【解决方案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'}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2021-11-13
    • 1970-01-01
    • 2021-06-24
    • 2021-05-26
    相关资源
    最近更新 更多