简体   繁体   中英

How to get Python dictionary with the highest key value?

I have a dictionary with latitude and longitude values passed from a different file.

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

If we print absoluteList we get:

{'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}

I need to print out the dictionary with the highest latitude value.

Just use 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}
print( max(absoluteList, key=lambda x: x['latitude']))

The are 2 ways to do it is by

  1. using itemgetter()

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

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

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM