从字典列表中获取具有最低键值的字典

时间:2016-04-22 22:24:05

标签: list python-3.x dictionary

从字典列表中我想获得'cost'键值最小的字典,然后从该字典中删除其他键值对

lst = [{'probability': '0.44076116',  'cost': '108.41'} , {'probability': '0.55923884',  'cost': '76.56'}]

2 个答案:

答案 0 :(得分:2)

您可以为min()内置功能提供自定义key功能:

>>> min(lst, key=lambda item: float(item['cost']))
{'cost': '76.56', 'probability': '0.55923884'}

或者,如果您只需要最低成本价值,您可以从成本值列表中找到最低成本价值:

costs = [float(item["cost"]) for item in lst]
print(min(costs))

答案 1 :(得分:2)

@ alecxe的解决方案很简洁,为他+1。这是我的方法:

>>> dict_to_keep = dict()
>>> min=1000000
>>> for d in lst:
...     if float(d["cost"]) < min:
...         min = float(d["cost"])
...         dict_to_keep = d
...
>>> print (dict_to_keep)
{'cost': '76.56', 'probability': '0.55923884'}