Home > Backend Development > Python Tutorial > How Can You Invert a Dictionary with List Values?

How Can You Invert a Dictionary with List Values?

Linda Hamilton
Release: 2024-10-29 04:23:02
Original
865 people have browsed it

How Can You Invert a Dictionary with List Values?

Inverting Dictionaries with List Values: A Solution

In this article, we explore the challenge of inverting a dictionary with list values. Given an index dictionary where keys are filenames and values are lists of words appearing in those files, we aim to create an inverted dictionary where words are keys and values are lists of filenames.

The provided inversion function, invert_dict, is not applicable to dictionaries with list values as keys, as it fails with a "TypeError: unhashable type: 'list'". This limitation stems from the fact that keys in dictionaries must be hashable, and lists are not hashable.

To overcome this hurdle, we can utilize a custom approach that iterates through the original dictionary and creates a new dictionary using setdefault. Specifically, we iterate through the value lists of each key in the original dictionary and add the corresponding keys as values for those words in the new inverted dictionary.

Here's an example implementation of this approach:

<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 handles list values in the original dictionary by using the setdefault method to create a new list if the key does not exist in the inverted dictionary, or append to an existing list if the key is already present.

As a result, we obtain an inverted dictionary where words are keys and values are lists of filenames.

The above is the detailed content of How Can You 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