Create a dictionary of even numbers as keys and their squares as values


This Python code creates a dictionary named evens_squared where the keys are even numbers from 0 to 20, and the values are the squares of those even numbers. Here's how the code works:

  • evens_squared = {x: x ** 2 for x in range(0, 21) if x % 2 == 0}: This line uses a dictionary comprehension to create the evens_squared dictionary. It iterates through each even number x in the range from 0 to 20 and assigns a key-value pair to the dictionary. The key is the even number itself (x), and the value is the square of that even number (x ** 2)
    • for x in range(0, 21): This part of the code iterates through each number from 0 to 20.
    • if x % 2 == 0: It checks if the number is even by using the modulo operator (%) to see if there is no remainder when dividing by 2.
  • print(evens_squared): This line prints the evens_squared dictionary to the console.

Source Code

evens_squared = {x: x ** 2 for x in range(0, 21) if x % 2 == 0}
print(evens_squared)

Output

0: 0, 2: 4, 4: 16, 6: 36, 8: 64, 10: 100, 12: 144, 14: 196, 16: 256, 18: 324, 20: 400}

Example Programs