Create a dictionary of numbers and their squares, but only for even numbers


This Python code takes a list of numbers and creates a dictionary even_squares where the keys are even numbers from the original list, and the values are the squares of those even numbers. Here's how the code works:

  • numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: This line initializes a list named numbers with ten integer values.
  • even_squares = {x: x ** 2 for x in numbers if x % 2 == 0}: This line uses a dictionary comprehension to create the even_squares dictionary. It iterates through each number x in the numbers list and assigns a key-value pair to the dictionary if and only if the number is even (i.e., if x % 2 == 0 is True). The key is the even number itself (x), and the value is the square of that even number (x ** 2).
    • for x in numbers: This part of the code iterates through each number in the numbers list.
    • if x % 2 == 0: This part of the code checks if the number is even by testing if it's divisible by 2 with no remainder.
  • print(numbers): This line prints the original numbers list to the console.
  • print(even_squares): This line prints the even_squares dictionary, which contains even numbers as keys and their squared values as values

Source Code

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = {x: x ** 2 for x in numbers if x % 2 == 0}
print(numbers)
print(even_squares)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Example Programs