Create a dictionary of numbers and their squares, excluding odd numbers


This Python code creates a dictionary named even_squares where the keys are even numbers from a 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 a sequence of numbers you want to analyze.
  • 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 checks if the number is even (using x % 2 == 0). For each even number, it assigns a key-value pair to the dictionary. The key is the even number itself (x), and the value is the square of that number (x ** 2).
    • for x in numbers: This part of the code iterates through each number in the numbers list.
    • if x % 2 == 0: It checks if the number is even (i.e., its remainder when divided by 2 is 0).
  • print(even_squares): This line prints the even_squares dictionary, which contains the squares of even numbers from the original list.

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(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