Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Multiply Python Dictionary Value by a Constant
Python dictionaries are versatile data structures that store key-value pairs. Sometimes we need to scale all dictionary values by multiplying them with a constant factor. This operation is useful for data normalization, unit conversion, or mathematical transformations.
What is Dictionary Value Multiplication?
Multiplying dictionary values by a constant means taking each numeric value in the dictionary and multiplying it by the same number. For example, if we have a dictionary of prices and want to apply a 10% increase, we multiply all values by 1.1.
Basic Dictionary Structure
# Basic dictionary syntax
prices = {'apple': 10, 'banana': 5, 'orange': 8}
print("Original dictionary:", prices)
Original dictionary: {'apple': 10, 'banana': 5, 'orange': 8}
Method 1: Using For Loop Iteration
The simplest approach uses a for loop to iterate through each key-value pair and multiply the values by the constant ?
# Multiply dictionary values using for loop
prices = {'apple': 10, 'banana': 5, 'orange': 8}
print("Original dictionary:", prices)
# Constant multiplier
multiplier = 1.2 # 20% increase
# Method 1: Direct assignment
for key in prices:
prices[key] = prices[key] * multiplier
print("After multiplication:", prices)
Original dictionary: {'apple': 10, 'banana': 5, 'orange': 8}
After multiplication: {'apple': 12.0, 'banana': 6.0, 'orange': 9.6}
Method 2: Using Dictionary Comprehension
Dictionary comprehension provides a more concise and Pythonic way to multiply values ?
# Multiply dictionary values using comprehension
prices = {'apple': 10, 'banana': 5, 'orange': 8}
multiplier = 1.5
# Create new dictionary with multiplied values
new_prices = {key: value * multiplier for key, value in prices.items()}
print("Original:", prices)
print("Multiplied:", new_prices)
Original: {'apple': 10, 'banana': 5, 'orange': 8}
Multiplied: {'apple': 15.0, 'banana': 7.5, 'orange': 12.0}
Method 3: Using NumPy for Large Datasets
For better performance with large datasets, NumPy provides optimized operations ?
import numpy as np
# Large dataset example
data = {'item1': 100, 'item2': 200, 'item3': 300, 'item4': 150}
multiplier = 0.8 # 20% discount
# Using NumPy multiply function
result = {key: np.multiply(value, multiplier) for key, value in data.items()}
print("Original data:", data)
print("After discount:", result)
Original data: {'item1': 100, 'item2': 200, 'item3': 300, 'item4': 150}
After discount: {'item1': 80.0, 'item2': 160.0, 'item3': 240.0, 'item4': 120.0}
Comparison of Methods
| Method | Performance | Memory Usage | Best For |
|---|---|---|---|
| For Loop | Good | Modifies original | Small datasets, in-place modification |
| Dictionary Comprehension | Better | Creates new dict | Medium datasets, functional style |
| NumPy | Best | Optimized | Large datasets, scientific computing |
Practical Example: Price Calculator
# Real-world example: applying tax to product prices
products = {
'laptop': 1000,
'mouse': 25,
'keyboard': 75,
'monitor': 300
}
tax_rate = 1.08 # 8% tax
# Calculate prices with tax
final_prices = {product: price * tax_rate for product, price in products.items()}
print("Prices before tax:")
for product, price in products.items():
print(f" {product}: ${price}")
print("\nPrices with 8% tax:")
for product, price in final_prices.items():
print(f" {product}: ${price:.2f}")
Prices before tax: laptop: $1000 mouse: $25 keyboard: $75 monitor: $300 Prices with 8% tax: laptop: $1080.00 mouse: $27.00 keyboard: $81.00 monitor: $324.00
Conclusion
Use dictionary comprehension for clean, readable code when creating new dictionaries. Use for loops for in-place modifications of small datasets. For large-scale data processing, NumPy provides optimal performance and memory efficiency.
