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>
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!