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

  • dict comprehension

    One of the ways to easily create dictionaries is through comprehension. Similar to the list comprehension, it’s possible to create a dict with an inline for loop:
    squares = {n: n**2 for n in range(1, 11)}
    print(squares)
    # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
    Just like in list or set comprehensions, all the rules of filtering or conditional elements apply for dict comprehension as well.
    names = ['Bob', 'Anna', 'Charles']
    surnames = ['Brown', 'Kennedy', 'Jackson']
    
    people = {names[i]: surnames[i] for i in range(len(names)) if names[i] != 'Anna'}
    print(people)
    # {'Bob': 'Brown', 'Charles': 'Jackson'}

    Challenge

    Given n numbers separated by a space, you are asked to create a dictionary that would map the number to its cube, while eliminating all the numbers whose square ends with 6.
    The only line of the input contains space-separated numbers.
    The program should print numbers that satisfy the condition with their cube.
    Input
    Output
    5 4 8 9 6 2 0 -4
    5 125 8 512 9 729 2 8 0 0
    Can you solve this in a single line 😎?
     
    To check your solution you need to sign in
    Sign in to continue