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

  • Safely accessing elements

    Writing an if statement to check if a key exists in the dictionary and then access it might get repetitive and annoying. That repetitive checks can be removed when accessing the elements safely through a .get() method:
    # Imagine we have a great team for a startup
    team = {
    	'HR': ['John Smith', 'Taylor Vu'],
    	'Designers': ['Garry Tan'],
    	'Developers': ['Linus Torvalds', 'Yegor Bugayenko'],
    }
    if 'HR' in team:
    	print(team['HR'])
    else:
    	print([])
    
    if 'QA' in team:
    	print(team['QA'])
    else:
    	print([])
    print(team.get('HR', []))
    print(team.get('QA', []))
    Here we access the team dictionary with a .get() method, where we provide the key as a first parameter (HR or QA), and a default value as a second parameter (an empty list in this example).
    Another example could be accessing a dictionary with some default value like a number or a string: population.get('China', '~1.5 Billion'). If key China exists in the dictionary population, the program will return its corresponding value. But if China is not in the population dictionary, the program will return '~1.5 Billion'.

    Challenge

    Antonym dictionary contains words that have opposite meanings. Given n antonym word pairs, you are asked to print q antonyms for the q words that follow, and Not found if those words are not found in the initial list. It’s guaranteed that the words in antonym pairs are unique.
    The first line of the input contains a single integer n which is the number of antonym pairs. The next n lines contain two words separated by a space that represents the antonym pairs. The next line contains a single integer q - the number of query words. The next q lines contain a single word.
    The program should print q lines. Each line should contain the antonym or Not found if the antonym is not present in the initial list.
    Input
    Output
    5 warm cold sunny cloudy fast slow tired energetic love hate 3 warm hate potato
    cold love Not found
     
    To check your solution you need to sign in
    Sign in to continue