Skip to main content

How to find the minimum value in a dictionary in Python

How to find the minimum value in a dictionary in Python.

Here's a step-by-step tutorial on how to find the minimum value in a dictionary in Python:

  1. First, create a dictionary with key-value pairs. For example, let's consider a dictionary that represents the ages of different people:

    ages = {
    'John': 25,
    'Emily': 30,
    'Michael': 20,
    'Jessica': 35
    }
  2. Next, you can use the min() function along with the values() method to find the minimum value in the dictionary. The values() method returns a view object that contains all the values from the dictionary.

    min_age = min(ages.values())
    print(min_age)

    Output:

    20

    In this example, the min() function is used to find the minimum value among the ages in the dictionary.

  3. If you also want to find the corresponding key for the minimum value, you can use a for loop to iterate through the dictionary and check each value against the minimum value. Here's an example:

    min_age = min(ages.values())

    for name, age in ages.items():
    if age == min_age:
    print('The person with the minimum age is:', name)

    Output:

    The person with the minimum age is: Michael

    This code iterates through each key-value pair in the dictionary and checks if the age matches the minimum age. If it does, it prints the corresponding name.

  4. Another approach is to use a list comprehension to create a list of keys that have the minimum value. Here's an example:

    min_age = min(ages.values())
    min_names = [name for name, age in ages.items() if age == min_age]
    print('The people with the minimum age are:', min_names)

    Output:

    The people with the minimum age are: ['Michael']

    In this example, a list comprehension is used to create a list of names where the age matches the minimum age.

These are the steps to find the minimum value in a dictionary in Python. You can choose the approach that suits your requirements best.