【问题标题】:Get dictionary with lowest key value from a list of dictionaries从字典列表中获取具有最低键值的字典
【发布时间】:2016-04-22 22:24:04
【问题描述】:

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

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

【问题讨论】:

    标签: list python-3.x dictionary


    【解决方案1】:

    您可以为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))
    

    【讨论】:

    • 我说的第二部分的任何 pythonic 建议:“然后从该字典中删除其他键、值对”?
    • @KristofPal 你可以通过这种方式得到最低的costmin(lst, key=lambda item: float(item['cost']))["cost"]..如果我理解这部分正确的话。谢谢。
    • @KristofPal 添加了一个选项,以防我们仍然在同一页面上:)
    【解决方案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'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-27
      • 2021-12-11
      • 2019-11-30
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多