"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can You Invert a Dictionary with List Values?

How Can You Invert a Dictionary with List Values?

Published on 2024-11-07
Browse:339

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:

inverse = {}
for k,v in index.items():
    for x in v:
        inverse.setdefault(x, []).append(k)

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3