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


This Python code creates a dictionary multiples_of_3_squares where the keys are numbers from a list, but only for those numbers that are multiples of 3, and the values are the squares of these 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.
  • multiples_of_3_squares = {x: x ** 2 for x in numbers if x % 3 == 0}: This line uses a dictionary comprehension to create the multiples_of_3_squares dictionary. It iterates through each number x in the numbers list and assigns a key-value pair to the dictionary only if the number is a multiple of 3 (i.e., when x % 3 == 0). The key is the 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 % 3 == 0: This part of the code checks whether the number x is a multiple of 3.
    • x: x ** 2: This part of the code creates the key-value pair. The key is the number x, and the value is its square, computed as x ** 2.
  • print(numbers): This line prints the original numbers list to the console.
  • print(multiples_of_3_squares): This line prints the multiples_of_3_squares dictionary, which contains numbers (that are multiples of 3) as keys and their squared values as values.

Source Code

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

Output

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

Example Programs