与 Python 中的词典列表相关联

Correlating to list of dictionaries in Python

我有两个包含字典的列表:

List1 = [{"Value": "Value1", "Start": 7.11, "End": 8},
         {"Value": "Value2", "Start": 16.45, "End": 20}]

List2 = [{"From":7.11, "To": 8, "Result": 0},
         {"From":16.45, "To": 20 "Result": 1}
        ]

我需要通过关联这些列表来生成一个列表。所以结果将是

Result = [{"Value": "Value1", "Start": 7.11, "End": 8, Result: 0},
         {"Value": "Value2", "Start": 16.45, "End": 20,Result: 1}]

这看起来很简单table加入SQL。

在 Python 中我该怎么做?

谢谢!

您可以使用嵌套字典理解:

List1 = [{"Value": "Value1", "Start": 7.11, "End": 8},
 {"Value": "Value2", "Start": 16.45, "End": 20}]

List2 = [{"From":7.11, "To": 8, "Result": 0},
 {"From":16.45, "To": 20, "Result": 1}
]

new_list = [{**a, **{'Result':b['Result']}} for a, b in zip(List1, List2)]

输出:

[{'Value': 'Value1', 'Start': 7.11, 'End': 8, 'Result': 0}, {'Value': 'Value2', 'Start': 16.45, 'End': 20, 'Result': 1}]

因为字典解包 (**) 只是 Python3 中的一个功能,您可以在 Python2 中使用 dict.items:

new_list = [dict(a.items()+[('Result', b['Result'])]) for a, b in zip(List1, List2)]

输出:

[{'Start': 7.11, 'End': 8, 'Result': 0, 'Value': 'Value1'}, {'Start': 16.45, 'End': 20, 'Result': 1, 'Value': 'Value2'}]