【问题标题】:How to get Python dictionary with the highest key value?如何获得具有最高键值的 Python 字典?
【发布时间】:2022-01-10 16:26:14
【问题描述】:

我有一本字典,其中包含从不同文件传递的纬度和经度值。

absoluteList = {"latitude": absolute[1], "longitude": absolute[0]}

如果我们打印absoluteList,我们会得到:

{'latitude': 507476711, 'longitude': -18299961}
{'latitude': 507447383, 'longitude': -18388366}
{'latitude': 507436793, 'longitude': -18459606}
{'latitude': 507427288, 'longitude': -18500804}
{'latitude': 507410993, 'longitude': -18521404}
{'latitude': 507395241, 'longitude': -18552732}
{'latitude': 507362921, 'longitude': -18550157}
{'latitude': 507344995, 'longitude': -18521404}

我需要打印出纬度值最高的字典。

【问题讨论】:

标签: python dictionary google-maps coordinates


【解决方案1】:

只需使用max:

absoluteList = [
  {'latitude': 507476711, 'longitude': -18299961},
  {'latitude': 507447383, 'longitude': -18388366},
  {'latitude': 507436793, 'longitude': -18459606},
  {'latitude': 507427288, 'longitude': -18500804},
  {'latitude': 507410993, 'longitude': -18521404},
  {'latitude': 507395241, 'longitude': -18552732},
  {'latitude': 507362921, 'longitude': -18550157},
  {'latitude': 507344995, 'longitude': -18521404}
]

biggest_latitude = max(absoluteList, key=lambda x: x['latitude'])
{'latitude': 507476711, 'longitude': -18299961}

【讨论】:

  • lambdaitemgetter()
  • @OlvinR​​oght 是的,性能用途 itemgetter 就像你在 cmets 中所说的那样。
【解决方案2】:
print( max(absoluteList, key=lambda x: x['latitude']))

【讨论】:

  • 最好使用itemgetter()
【解决方案3】:

有两种方法可以做到这一点

  1. 使用itemgetter()

     from operator import itemgetter 
    highest_value_in_list = max(absoluteList, key=itemgetter('latitude'))`
    
  2. 使用max:

    highest_value_in_list = max(absoluteList, key=lambda x: x['latitude'])

输出:

{'latitude': 507476711, 'longitude': -18299961}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 2020-07-22
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多