w3resource

Python merging OrderedDicts with summed values


Write a Python function that merges two OrderedDict objects. If there are duplicate keys, sum their values. Print the merged OrderedDict.

OrderedDict - 1
'Laptop': 40
'Desktop': 45
'Mobile': 35
OrderedDict - 2
'Laptop': 40
'Charger': 25

Sample Solution:

Code:

from collections import OrderedDict

def merge_ordered_dicts(dict1, dict2):
    merged_dict = OrderedDict()

    for key, value in dict1.items():
        if key in merged_dict:
            merged_dict[key] += value
        else:
            merged_dict[key] = value

    for key, value in dict2.items():
        if key in merged_dict:
            merged_dict[key] += value
        else:
            merged_dict[key] = value

    return merged_dict

# Create OrderedDict objects
ordered_dict1 = OrderedDict([
    ('Laptop', 40),
    ('Desktop', 45),
    ('Mobile', 35)
])
print("\nOrderedDict-1:",ordered_dict1)

ordered_dict2 = OrderedDict([
    ('Laptop', 40),
    ('Charger', 25)
])
print("\nOrderedDict-2:",ordered_dict2)
# Merge and print the merged OrderedDict
merged_ordered_dict = merge_ordered_dicts(ordered_dict1, ordered_dict2)
print("\nMerged Dictionary: ",merged_ordered_dict)

Output:

OrderedDict-1: OrderedDict([('Laptop', 40), ('Desktop', 45), ('Mobile', 35)])
OrderedDict-2: OrderedDict([('Laptop', 40), ('Charger', 25)])
Merged Dictionary:  OrderedDict([('Laptop', 80), ('Desktop', 45), ('Mobile', 35), ('Charger', 25)])

In the exercise above, the "merge_ordered_dicts()" function takes two OrderedDict objects as input ('ordered_dict1', 'ordered_dict2') and returns a new OrderedDict containing the merged and summed key-value pairs. The function iterates through both input dictionaries. The value of an existing key in the merged dictionary is added to the existing value if it already exists. Otherwise, it adds the key-value pair to the merged dictionary.

Flowchart:

Flowchart: Python merging OrderedDicts with summed values.

Previous: Python OrderedDict Key-Value removal.
Next: Python Removing key-Value pair from OrderedDict.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.