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

How Can I Efficiently Merge Python Dictionaries with Duplicate Keys?

Patricia Arquette
Release: 2024-12-14 14:11:11
Original
993 people have browsed it

How Can I Efficiently Merge Python Dictionaries with Duplicate Keys?

Merging Dictionaries with Duplicate Keys

In Python, dictionaries are used to store collections of key-value pairs. When dealing with multiple dictionaries with duplicate keys, merging them while maintaining the associated values can be a common challenge.

One efficient method for achieving this is through the use of the collections.defaultdict from the Python standard library. This specialized dictionary allows for value initialization with a default factory, such as a list, for non-existent keys.

Consider the following sample dictionaries:

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

To merge these dictionaries, we can initialize a defaultdict with a default value of an empty list:

dd = defaultdict(list)
Copy after login

Next, we iterate over each dictionary in the sequence along with their key-value pairs:

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

In this loop, for each key encountered, we append the corresponding value to the default list. This approach ensures that all duplicate keys are handled with their associated values.

As a result, the dd dictionary will contain merged values corresponding to duplicate keys:

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

This method is particularly useful when dealing with large sets of dictionaries or when there can be an arbitrary number of input dictionaries. It efficiently merges all duplicate keys while preserving their values in a consolidated output dictionary.

The above is the detailed content of How Can I Efficiently Merge Python Dictionaries with Duplicate Keys?. 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