Python | Multiply Dictionary Value by Constant

Python | Multiply Dictionary Value by Constant

To multiply all values in a dictionary by a constant in Python, you can iterate over the dictionary and multiply each value by the constant. Here's a simple way to do it using dictionary comprehension:

# Given dictionary my_dict = {'a': 1, 'b': 2, 'c': 3} # Constant to multiply with constant = 4 # Dictionary comprehension to multiply all values by the constant new_dict = {k: v * constant for k, v in my_dict.items()} print(new_dict) 

This will output a new dictionary with each value multiplied by 4:

{'a': 4, 'b': 8, 'c': 12} 

If you want to update the existing dictionary in place, you can iterate through the keys and update the values:

# Given dictionary my_dict = {'a': 1, 'b': 2, 'c': 3} # Constant to multiply with constant = 4 # Update dictionary in place for key in my_dict: my_dict[key] *= constant print(my_dict) 

The output will be the same, but the original dictionary my_dict is modified instead of creating a new one:

{'a': 4, 'b': 8, 'c': 12} 

More Tags

fencepost devexpress keychain hibernate-annotations detox java-platform-module-system ftp4j jmeter-3.2 statsmodels scikit-image

More Programming Guides

Other Guides

More Programming Examples