How to merge dictionaries by a key in Python with a class

This code defines a DataMerger class that collects dictionary records and merges them by a specified key, combining fields from multiple records with the same key.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 13 views 0 copies

Python code

34 lines
Python 3.9+
class DataMerger:
    def __init__(self):
        self.records = []

    def add_record(self, record):
        if isinstance(record, dict):
            self.records.append(record)
        else:
            raise TypeError("Record must be a dictionary")

    def merge_by_key(self, key):
        merged = {}
        for record in self.records:
            record_key = record.get(key)
            if record_key is None:
                continue
            if record_key not in merged:
                merged[record_key] = {}
            merged[record_key].update(record)
        return merged

    def get_all_records(self):
        return self.records


if __name__ == "__main__":
    merger = DataMerger()
    merger.add_record({"id": 1, "name": "Alice", "age": 30})
    merger.add_record({"id": 1, "city": "New York"})
    merger.add_record({"id": 2, "name": "Bob", "age": 25})
    merger.add_record({"id": 2, "city": "London"})

    result = merger.merge_by_key("id")
    print(result)

Output

stdout
{1: {'id': 1, 'name': 'Alice', 'age': 30, 'city': 'New York'}, 2: {'id': 2, 'name': 'Bob', 'age': 25, 'city': 'London'}}

How it works

The DataMerger class stores records in a list via the add_record method, which validates that each record is a dictionary. The merge_by_key method groups records by the value of the specified key, using a dictionary to accumulate merged data. For each record, it retrieves the key value and skips records without that key. It then merges the record into the existing group with update, so later records overwrite earlier fields with the same keys. This pattern is useful for combining fragmented data about the same entity.

Common mistakes

  • Forgetting to validate input type in add_record, leading to errors later.
  • Using `key in record` instead of `record.get(key)` and mishandling missing keys.
  • Not resetting the merged dictionary between calls, causing stale data.
  • Assuming the key always exists in every record, causing KeyError if using direct access.

Variations

  1. Use a defaultdict(dict) to simplify the initialization of each group.
  2. Implement merge_by_key as a standalone function instead of a class method.

Real-world use cases

  • Combining user profile updates from different microservices into a single view.
  • Merging configuration overrides from multiple sources into one settings object.
  • Consolidating logs or events with the same request ID into a single record.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.