【问题标题】:How to extract values based on keys from a list of `dict` objects in Python如何从 Python 中的“dict”对象列表中基于键提取值
【发布时间】:2021-09-03 00:15:43
【问题描述】:

我有一个列表sample_list 看起来像这样:

[{'ID': '123456', 'price': '1.111'}, {'ID': '987654', 'price': '200.888'}, {'ID': '789789', 'price': '0.212'},{..},...]

它包含多个dict 对象,现在我想编写一个函数,将ID 列表作为输入并返回相应的price,类似于:

def mapping_data(ids: list) -> map:
    mapping_data['123456'] = '1.111
    return mapping_data

实现这一目标的最简单方法是什么?

【问题讨论】:

    标签: python-3.x list dictionary mapping


    【解决方案1】:

    您可以使用简单的list_comprehensionif condition

    def mapping_data(ids):
        return [d['price'] for id in ids for d in l if d['ID'] == id]
    

    完整代码:

    l = [{'ID': '123456', 'price': '1.111'}, {'ID': '987654',
                                              'price': '200.888'}, {'ID': '789789', 'price': '0.212'}]
    
    
    def mapping_data(ids):
        return [d['price'] for id in ids for d in l if d['ID'] == id]
    
    
    mapping_data(['987654', '123456']) #prints ['200.888', '1.111']
    

    如果您需要 id 详细信息,也可以使用dict_comprehension

    def mapping_data(ids):
        return {id:d['price'] for id in ids for d in l if d['ID'] == id}
    # prints {'987654': '200.888', '123456': '1.111'}
    

    更好的选择:

    1. Dict_comprehension:
    def mapping_data(ids):
        return {i['ID']:i['price'] for i in l if i['ID'] in ids}
    
    
    mapping_data(['987654', '123456']) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2021-10-10
      • 1970-01-01
      相关资源
      最近更新 更多