如何根据 Python 中的 `dict` 对象列表中的键提取值
How to extract values based on keys from a list of `dict` objects in Python
我有一个列表 sample_list
看起来像这样:
[{'ID': '123456', 'price': '1.111'}, {'ID': '987654', 'price': '200.888'}, {'ID': '789789', 'price': '0.212'},{..},...]
它包含多个 dict
对象,现在我想写一个函数,它将 ID
的列表作为输入和 return 对应的 price
,类似:
def mapping_data(ids: list) -> map:
mapping_data['123456'] = '1.111
return mapping_data
实现此目标的最简单方法是什么?
您可以使用简单的 list_comprehension
和 if 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'}
更好的选择:
Dict_comprehension
:
def mapping_data(ids):
return {i['ID']:i['price'] for i in l if i['ID'] in ids}
mapping_data(['987654', '123456'])
我有一个列表 sample_list
看起来像这样:
[{'ID': '123456', 'price': '1.111'}, {'ID': '987654', 'price': '200.888'}, {'ID': '789789', 'price': '0.212'},{..},...]
它包含多个 dict
对象,现在我想写一个函数,它将 ID
的列表作为输入和 return 对应的 price
,类似:
def mapping_data(ids: list) -> map:
mapping_data['123456'] = '1.111
return mapping_data
实现此目标的最简单方法是什么?
您可以使用简单的 list_comprehension
和 if 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'}
更好的选择:
Dict_comprehension
:
def mapping_data(ids):
return {i['ID']:i['price'] for i in l if i['ID'] in ids}
mapping_data(['987654', '123456'])