Create a dictionary of numbers and their squares, but only for numbers greater than 5


Creates a dictionary named squares_greater_than_5, where the keys are numbers from a list that are greater than 5, and the values are the squares of those 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.
  • squares_greater_than_5 = {x: x ** 2 for x in numbers if x > 5}: This line uses a dictionary comprehension to create the squares_greater_than_5 dictionary. It iterates through each number in the numbers list and checks if the number is greater than 5. If the condition is met, it creates a key-value pair in the dictionary.
    • for x in numbers: This part of the code iterates through each number in the numbers list.
    • squares_greater_than_5 = {x: x ** 2 for x in numbers if x > 5}: For each number, it takes the number itself as the key and calculates the square of the number using the expression x ** 2, creating the value.
    • if x > 5: This condition ensures that only numbers greater than 5 are included in the dictionary.
  • print(numbers): This line prints the original numbers list to the console.
  • print(squares_greater_than_5): This line prints the squares_greater_than_5 dictionary, which contains numbers greater than 5 as keys and their corresponding squares as values.

Source Code

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

Output

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

Example Programs