Python - Multiplication across Like Keys Value list elements

In Python, when working with a list of dictionaries, you often need to perform operations across dictionaries with similar keys. One common task is multiplying values for the same keys across all dictionaries in the list.

Understanding the Problem

Given a list of dictionaries with identical keys, we need to multiply the values for each key across all dictionaries. For example, if we have three dictionaries with key 'A', we multiply all the values associated with 'A' together.

Algorithm

  • Step 1 Initialize an empty dictionary to store the multiplication results

  • Step 2 Iterate through each dictionary in the input list

  • Step 3 For each key-value pair, check if the key exists in the result dictionary

  • Step 4 If the key doesn't exist, initialize it with the current value

  • Step 5 If the key exists, multiply the existing value with the current value

  • Step 6 Return the result dictionary with multiplied values

Implementation

def multiply_like_keys(dict_list):
    """Multiply values for like keys across dictionaries"""
    result = {}
    
    for dictionary in dict_list:
        for key, value in dictionary.items():
            if key not in result:
                result[key] = value
            else:
                result[key] *= value
    
    return result

# Sample data
fruit_data = [
    {'Grape': 3, 'Peach': 5, 'Cherry': 2},
    {'Grape': 4, 'Peach': 4, 'Cherry': 5},
    {'Grape': 5, 'Peach': 2, 'Cherry': 3}
]

# Calculate multiplication
output = multiply_like_keys(fruit_data)
print("Multiplication result:", output)
Multiplication result: {'Grape': 60, 'Peach': 40, 'Cherry': 30}

Using collections.defaultdict

An alternative approach uses defaultdict to simplify initialization ?

from collections import defaultdict

def multiply_with_defaultdict(dict_list):
    """Using defaultdict for cleaner code"""
    result = defaultdict(lambda: 1)
    
    for dictionary in dict_list:
        for key, value in dictionary.items():
            result[key] *= value
    
    return dict(result)

# Sample data
numbers = [
    {'a': 2, 'b': 3, 'c': 4},
    {'a': 5, 'b': 2, 'c': 1},
    {'a': 3, 'b': 4, 'c': 2}
]

output = multiply_with_defaultdict(numbers)
print("Result:", output)
Result: {'a': 30, 'b': 24, 'c': 8}

Handling Missing Keys

When dictionaries don't have all the same keys, we can handle missing values ?

def multiply_with_missing_keys(dict_list, default_value=1):
    """Handle cases where not all dictionaries have the same keys"""
    all_keys = set()
    for dictionary in dict_list:
        all_keys.update(dictionary.keys())
    
    result = {}
    for key in all_keys:
        product = 1
        for dictionary in dict_list:
            product *= dictionary.get(key, default_value)
        result[key] = product
    
    return result

# Data with missing keys
mixed_data = [
    {'x': 2, 'y': 3},
    {'x': 4, 'z': 5},
    {'y': 2, 'z': 3}
]

output = multiply_with_missing_keys(mixed_data)
print("Result with missing keys:", output)
Result with missing keys: {'x': 8, 'y': 6, 'z': 15}

Comparison

Method Handles Missing Keys Code Complexity Best For
Basic Loop No Simple Uniform dictionaries
defaultdict Yes (with default 1) Medium Cleaner initialization
Missing Key Handler Yes (configurable) Complex Non-uniform dictionaries

Time Complexity

The time complexity is O(n × m), where n is the number of dictionaries and m is the average number of key-value pairs per dictionary. Each key-value pair is processed exactly once.

Conclusion

Multiplying values across like keys in a list of dictionaries is straightforward with basic iteration. Use defaultdict for cleaner code or implement missing key handling for non-uniform data structures.

Updated on: 2026-03-27T15:32:34+05:30

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements