Create a dictionary of squares of numbers from 1 to 10
This Python code creates a dictionary named squares where the keys are numbers from 1 to 10, and the values are the squares of those numbers. Here's how the code works:
- squares = {x: x ** 2 for x in range(1, 11)} : This line uses a dictionary comprehension to create the squares dictionary. It iterates through each number x in the range from 1 to 10 and assigns a key-value pair to the dictionary. The key is the number itself (x), and the value is the square of that number (x ** 2).
- for x in range(1, 11): This part of the code iterates through each number from 1 to 10.
- print(squares): This line prints the squares dictionary to the console.
Source Code
squares = {x: x ** 2 for x in range(1, 11)}
print(squares)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}