fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • keys values items

    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:
    population = {
    	'US': 3295000000,
    	'Mexico': 129000000,
    	'Armenia': 3000000,
    	'Portugal': 10300000
    }
    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
    Anna: 103.33333333333333 Ani: 110 Bob: 90
     
    To check your solution you need to sign in
    Sign in to continue