Create a dictionary of numbers and their cubes


This Python code creates a dictionary named cubes where the keys are numbers from a list, and the values are the cubes of those numbers. Here's how the code works:

  • numbers = [1, 2, 3, 4, 5]: This line initializes a list named numbers with a sequence of numbers you want to analyze.
  • cubes = {x: x ** 3 for x in numbers}: This line uses a dictionary comprehension to create the cubes dictionary. It iterates through each number x in the numbers list and assigns a key-value pair to the dictionary. The key is the number itself (x), and the value is the cube of that number (x ** 3).
    • for x in numbers: This part of the code iterates through each number in the numbers list.
  • print(numbers): This line prints the original numbers list to the console.
  • print(cubes): This line prints the cubes dictionary, which contains the cubes of the numbers from the original list.

Source Code

numbers = [1, 2, 3, 4, 5]
cubes = {x: x ** 3 for x in numbers}
print(numbers)
print(cubes)

Output

[1, 2, 3, 4, 5]
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

Example Programs