ByteBoard Notes Notes

To print the highest and lowest values in a dictionary

Informatics Practices XI · Experiment 17 of 36 · Python

★ CBSE suggested11-IPPython programs
Expt. No.17
Page No.34

Highest and lowest in a dictionary

Aim

To write a Python program that finds the highest and lowest values in a dictionary, and the keys they belong to.

Concepts used

Algorithm

  1. Create a dictionary of items and prices.
  2. Find the highest and lowest values with max() and min() on values().
  3. Loop through the dictionary to find the keys that have those values.
  4. Display them.

Program

# Highest and lowest values in a dictionary price = {"Pen": 20, "Notebook": 65, "Bag": 850, "Eraser": 5, "Box": 120}print("Dictionary:", price) high = max(price.values())low = min(price.values())for item in price:    if price[item] == high:        print("Highest value:", high, "(", item, ")")    if price[item] == low:        print("Lowest value :", low, "(", item, ")")

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python highest_lowest_dictionary.py
Dictionary: {'Pen': 20, 'Notebook': 65, 'Bag': 850, 'Eraser': 5, 'Box': 120} Highest value: 850 ( Bag ) Lowest value : 5 ( Eraser )

✓ Printed by running this program, not typed by hand.

Result

The highest value was 850 (Bag) and the lowest 5 (Eraser).

Viva voce: what the examiner may ask

01What does price.values() give?

All the values of the dictionary (the prices).

02What would max(price) give instead?

The largest key in alphabetical order ("Pen"), not the largest price.

03What does items() return?

The key-value pairs of the dictionary.

Variations for the lab test

  1. Display the total of all values.
  2. Display the items that cost more than 100.
  3. Increase every price by 10%.
! Common mistake Using max(price) compares the keys (names), not the values.
Back to the 11-IP index