Create a dictionary of numbers and their powers of 2


This Python code creates a dictionary powers_of_2, where the keys are numbers from a list, and the values are 2 raised to the power of each number. Here's how the code works:

  • numbers = [1, 2, 3, 4, 5]: This line initializes a list named numbers with five integer values.
  • powers_of_2 = {x: 2 ** x for x in numbers}: This line uses a dictionary comprehension to create the powers_of_2 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 calculated by raising 2 to the power of that number (2 ** x).
    • for x in numbers: This part of the code iterates through each number in the numbers list.
    • x: 2 ** x: This part of the code creates the key-value pair. The key is the number x, and the value is calculated as 2 ** x, which raises 2 to the power of the number x.
  • print(numbers): This line prints the original numbers list to the console.
  • print(powers_of_2): This line prints the powers_of_2 dictionary, which contains numbers as keys and their corresponding powers of 2 as values.

Source Code

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

Output

[1, 2, 3, 4, 5]
{1: 2, 2: 4, 3: 8, 4: 16, 5: 32}

Example Programs