Home > Backend Development > Python Tutorial > How Can I Efficiently Merge Dictionaries with Duplicate Keys and Collect Their Values?

How Can I Efficiently Merge Dictionaries with Duplicate Keys and Collect Their Values?

Patricia Arquette
Release: 2024-12-24 15:29:12
Original
688 people have browsed it

How Can I Efficiently Merge Dictionaries with Duplicate Keys and Collect Their Values?

Merging Dictionaries for Duplicate Keys

When working with multiple dictionaries containing overlapping keys, it becomes necessary to efficiently merge them while collecting values associated with those keys. This article explores a solution to combine and collect values from matching keys within a collection of dictionaries.

Problem Statement

Given several dictionaries like:

d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}
Copy after login

The goal is to obtain a merged result as a new dictionary, where each key holds a tuple of values from the original dictionaries:

d = {key1: (x1, x2), key2: (y1, y2)}
Copy after login

Solution

The solution utilizes the collections.defaultdict to create a dictionary with default values as mutable lists. This allows the accumulation of values for each key:

from collections import defaultdict

d1 = {1: 2, 3: 4}
d2 = {1: 6, 3: 7}

dd = defaultdict(list)

for d in (d1, d2): # Input dictionaries can be iterated over here
    for key, value in d.items():
        dd[key].append(value)
Copy after login

The final merged dictionary dd contains each key mapped to a list of values from the input dictionaries.

The above is the detailed content of How Can I Efficiently Merge Dictionaries with Duplicate Keys and Collect Their Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template