When working with dictionaries, it’s sometimes important to iterate over all the keys, or maybe all the values, or sometimes all the key-value pairs. Accessing all the keys is possible through the keys() method. Accessing all the values is possible through the values() method, while accessing the key-value pairs is possible through the items() method:
for k in population.keys():
print(k.lower())
# Or even
for k in population:
print(k.lower())
# us
# mexico
# armenia
# portugal
for v in population.values():
print(v * 2)
# 6590000000
# 258000000
# 6000000
# 20600000
# population.items() is a list of tuples
# each tuple is a (key, value) pair: ('US', 3295000000)
for k, v in population.items():
print(f'{k.lower()}: {v * 2}')
# Alternatively
for k in population:
print(f'{k.lower()}: {population[k] * 2}')
# us: 6590000000
# mexico: 258000000
# armenia: 6000000
# portugal: 20600000
Challenge
Given a list of n patients with their blood pressure measurements, you are asked to calculate the average blood pressure for each patient. There are m measurements, each of the form patient-name: blood-pressure.
The first line of the input contains a single integer m. The next m lines contain the measurements of the form patient-name: blood-pressure.
The program should print the average blood pressure per patient in the order of appearance in the input. The format should be similar to the input patient-name: average-blood-pressure.
Input
Output
6
Anna: 100
Ani: 120
Anna: 120
Anna: 90
Ani: 100
Bob: 90