Python - Maximum record value key in dictionary

Python - Maximum record value key in dictionary

To find the key with the maximum value in a dictionary in Python, you can use the max() function along with a key argument. The key argument specifies a one-argument ordering function like the values or a lambda function to compare the values.

Here's an example:

# Example dictionary records = { 'Alice': 50, 'Bob': 75, 'Charlie': 90, 'Diana': 85 } # Find the key with the maximum value max_key = max(records, key=records.get) print(f"Key with maximum value: {max_key}") 

In this code:

  • records is a dictionary with names as keys and numbers as values.
  • The max() function is used to find the key with the maximum value. The key=records.get argument tells max() to compare the values of the dictionary (records.get returns the value for a given key).

This method is efficient and concise, and it works well with dictionaries containing any kind of comparable values.


More Tags

nested-documents expo page-break-inside donut-chart spring-profiles floating-point entity-framework-migrations stringbuilder java-8 django-filters

More Programming Guides

Other Guides

More Programming Examples