Create a dictionary of numbers and their binary representations


This Python code takes a list of numbers and creates a dictionary binary_representations where the keys are the numbers from the original list, and the values are their binary representations as strings. Here's how the code works:

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

Source Code

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

Output

[1, 2, 3, 4, 5]
{1: '0b1', 2: '0b10', 3: '0b11', 4: '0b100', 5: '0b101'}

Example Programs