Create a dictionary of numbers and their prime status


This Python code defines a function is_prime(n) that checks if a given number n is prime. It then uses a dictionary comprehension to create a dictionary named prime_status where the keys are numbers from a list, and the values are Boolean values indicating whether each number is prime or not. Here's how the code works:

  • def is_prime(n): This defines a function is_prime that takes a single argument n and checks if it's a prime number. The function returns True if n is prime and False otherwise. It uses a standard primality check algorithm, testing divisors up to the square root of n.
  • numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] : This line initializes a list named numbers with a sequence of numbers you want to analyze.
  • prime_status = {x: is_prime(x) for x in numbers}: This line uses a dictionary comprehension to create the prime_status 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 result of calling the is_prime function on that number, which determines if it's prime or not.
    • for x in numbers: This part of the code iterates through each number in the numbers list.
    • {x: is_prime(x) for x in numbers}: It uses a dictionary comprehension to create key-value pairs where the key is the number x, and the value is the result of the is_prime function for that number.
  • print(numbers): This line prints the original numbers list to the console.
  • print(prime_status): This line prints the prime_status dictionary, which contains the prime status (True or False) for each number in the original list.

Source Code

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True
 
 
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
prime_status = {x: is_prime(x) for x in numbers}
print(numbers)
print(prime_status)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
{1: False, 2: True, 3: True, 4: False, 5: True, 6: False, 7: True, 8: False, 9: False, 10: False}

Example Programs