Create a dictionary of numbers and their parity (even or odd)


This Python code takes a list of numbers and creates a dictionary parity where the keys are the numbers from the original list, and the values indicate whether each number is "even" or "odd." Here's how the code works:

  • numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] : This line initializes a list named numbers with ten integer values.
  • parity = {x: 'even' if x % 2 == 0 else 'odd' for x in numbers}: This line uses a dictionary comprehension to create the parity 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 determined using a conditional expression:
    • If x % 2 == 0, it's considered "even." Otherwise, it's considered "odd."
    • for x in numbers: This part of the code iterates through each number in the numbers list.
    • x: 'even' if x % 2 == 0 else 'odd': This part of the code creates the key-value pair. The key is the number x, and the value is either 'even' or 'odd' based on the result of the conditional expression.
  • print(numbers): This line prints the original numbers list to the console.
  • print(parity): This line prints the parity dictionary, which contains numbers as keys and their parity (even or odd) as values.

Source Code

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
parity = {x: 'even' if x % 2 == 0 else 'odd' for x in numbers}
print(numbers)
print(parity)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd', 10: 'even'}

Example Programs