Home > Backend Development > Python Tutorial > How Can I Efficiently Merge Python Dictionaries with Matching Keys into Tuples of Values?

How Can I Efficiently Merge Python Dictionaries with Matching Keys into Tuples of Values?

Linda Hamilton
Release: 2024-12-22 14:25:17
Original
1001 people have browsed it

How Can I Efficiently Merge Python Dictionaries with Matching Keys into Tuples of Values?

Merging Dictionaries with Matching Keys: A Tutorial

In Python, merging dictionaries by combining values associated with matching keys can be a common task. Let's explore a method to efficiently achieve this goal.

Problem Statement

Given multiple dictionaries with key-value pairs, such as:

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

The objective is to create a new dictionary where each key has a tuple of the corresponding values from the input dictionaries. For instance, the desired result would be:

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

Solution: Utilizing defaultdict

One efficient approach to merge dictionaries while collecting values from matching keys is to leverage the defaultdict class from the collections module. Here's a step-by-step demonstration:

  1. Define a defaultdict object, which automatically creates lists for missing keys.
  2. Iterate over the input dictionaries.
  3. For each dictionary, for each key-value pair, append the value to the list associated with the key in the defaultdict.
  4. The resulting defaultdict will have keys representing the original keys from all input dictionaries, and values as lists containing the corresponding values.

Code Implementation

from collections import defaultdict

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

dd = defaultdict(list)

for d in (d1, d2):
    for key, value in d.items():
        dd[key].append(value)

print(dd)  # defaultdict(<type 'list'>, {1: [2, 6], 3: [4, 7]})
Copy after login

By following these steps, you can effectively merge dictionaries with matching keys and combine their associated values into a new dictionary.

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

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