代码之家  ›  专栏  ›  技术社区  ›  leon

与python中的词典列表相关

  •  2
  • leon  · 技术社区  · 7 年前

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

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

    这看起来像是sql中的简单表连接。

    我怎么用Python呢?

    谢谢!

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ajax1234    7 年前

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

    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中的一个特性,您可以使用 dict.items 在Python2中:

    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'}]
    
    推荐文章