Create a dictionary of numbers with their signs reversed
The list of numbers and creates a dictionary named reversed_signs. This dictionary maps each number to its negation (changing its sign from positive to negative or vice versa). Here's how the code works:
- numbers = [5, -10, 15, -20, 25]: This line initializes the numbers variable with a list of integers, including both positive and negative numbers.
- reversed_signs = {x: -x for x in numbers}: This line uses a dictionary comprehension to create the reversed_signs dictionary. It iterates through each number x in the numbers list.
- {x: -x}: This part of the code creates key-value pairs in the dictionary. The key is the original number x, and the value is the negation of that number, which is calculated as -x.
- print(numbers): This line prints the original list of numbers, numbers, to the console.
- print(reversed_signs): This line prints the reversed_signs dictionary, which contains the original numbers as keys and their negations as values.
Source Code
numbers = [5, -10, 15, -20, 25]
reversed_signs = {x: -x for x in numbers}
print(numbers)
print(reversed_signs)
Output
[5, -10, 15, -20, 25]
{5: -5, -10: 10, 15: -15, -20: 20, 25: -25}