Create a dictionary of numbers and their factors


This Python code takes a list of numbers and creates a dictionary factors where the keys are the numbers from the original list, and the values are lists of their factors. Here's how the code works:

  • numbers = [1, 2, 3, 4, 5]: This line initializes a list named numbers with five integer values.
  • factors = {x: [i for i in range(1, x + 1) if x % i == 0] for x in numbers}: This line uses a dictionary comprehension to create the factors 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 a list of its factors.
    • for x in numbers: This part of the code iterates through each number in the numbers list.
    • x: [i for i in range(1, x + 1) if x % i == 0]: This part of the code uses a list comprehension to generate a list of factors for each number. It iterates through numbers from 1 to x (inclusive) and includes only those numbers for which x % i == 0 is True. This condition checks if i is a factor of x.
  • print(numbers): This line prints the original numbers list to the console.
  • print(factors): This line prints the factors dictionary, which contains numbers as keys and lists of their factors as values.

Source Code

numbers = [1, 2, 3, 4, 5]
factors = {x: [i for i in range(1, x + 1) if x % i == 0] for x in numbers}
print(numbers)
print(factors)

Output

[1, 2, 3, 4, 5]
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 2, 4], 5: [1, 5]}

Example Programs