Home >Backend Development >Python Tutorial >How Can I Merge Python Dictionaries with Duplicate Keys into Lists of Values?

How Can I Merge Python Dictionaries with Duplicate Keys into Lists of Values?

DDD
DDDOriginal
2024-12-10 07:16:16496browse

How Can I Merge Python Dictionaries with Duplicate Keys into Lists of Values?

Merging Dictionaries with Duplicate Keys in Python

In Python, dealing with multiple dictionaries can be challenging, especially when merging them becomes necessary. A common issue arises when dictionaries share duplicate keys, and the goal is to collect all values associated with these keys into a single list.

Solution: defaultdict

To handle this efficiently, a powerful Python tool called defaultdict from the collections module comes into play. It allows for creating a default value (in this case, an empty list) for any key that doesn't exist in the dictionary.

Consider the following example:

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

To merge these dictionaries, collecting values from matching keys, we can use defaultdict as follows:

from collections import defaultdict

dd = defaultdict(list)

for d in (d1, d2): # loop through all input dictionaries
    for key, value in d.items():
        dd[key].append(value)
    
print(dd) # result: defaultdict(<type 'list'>, {1: [2, 6], 3: [4, 7]})

In this code:

  • We create an empty defaultdict with defaultdict(list).
  • We iterate through each input dictionary d.
  • For each key-value pair in each dictionary, we append the value to the list associated with the key in our defaultdict.
  • The result is a defaultdict where keys represent the merged keys from all dictionaries, and the values are lists containing all the corresponding values.

This solution efficiently collects all values associated with matching keys from multiple dictionaries, providing a clean and versatile way to handle duplicate keys.

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

Statement:
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