How to Invert a Dictionary with List Values?

Mary-Kate Olsen
Release: 2024-10-29 18:39:56
Original
903 people have browsed it

How to Invert a Dictionary with List Values?

Reversing a Dictionary with List Values

Your goal is to invert a dictionary (index) with list values such that the resulting dictionary (inverse) has duplicate values merged into one key with the original keys as values.

The provided function, invert_dict, fails when encountering list values due to the unhashable nature of lists. To resolve this, consider the following solution:

<code class="python">inverse = {}
for k, v in index.items():
    for x in v:
        inverse.setdefault(x, []).append(k)</code>
Copy after login

This solution iterates through the original dictionary (index), accessing each key (k) and value (v). For each value in v (which is a list), it adds the associated key to a list in the inverse dictionary using the setdefault method. The method creates a new entry for each unique value in v and appends the key to the associated list.

As a result, the inverse dictionary will contain the desired inverted structure, with each value being a list of original keys where that value appears.

The above is the detailed content of How to Invert a Dictionary with List 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!