Create a dictionary of numbers and their factorials


This Python code creates a dictionary factorials where the keys are numbers from a list, and the values are their factorial values computed using the math.factorial function. Here's how the code works:

  • numbers = [1, 2, 3, 4, 5]: This line initializes a list named numbers with five integer values.
  • factorials = {x: math.factorial(x) for x in numbers}: This line uses a dictionary comprehension to create the factorials 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 its factorial computed using the math.factorial function.
    • for x in numbers: This part of the code iterates through each number in the numbers list.
    • x: math.factorial(x): This part of the code creates the key-value pair. The key is the number x, and the value is its factorial value computed using math.factorial(x).
  • print(numbers): This line prints the original numbers list to the console.
  • print(factorials): This line prints the factorials dictionary, which contains numbers as keys and their factorial values as values.

Source Code

import math
 
numbers = [1, 2, 3, 4, 5]
factorials = {x: math.factorial(x) for x in numbers}
print(numbers)
print(factorials)

Output

[1, 2, 3, 4, 5]
{1: 1, 2: 2, 3: 6, 4: 24, 5: 120}

Example Programs