Inverting Dictionaries with List Values
The task at hand is to invert a dictionary whose values are lists, transforming it into a dictionary where each value from the original dictionary becomes a key in the new dictionary, with a list of the original keys as its value.
Given the following index dictionary:
index = { 'Testfil2.txt': ['nisse', 'hue', 'abe', 'pind'], 'Testfil1.txt': ['hue', 'abe', 'tosse', 'svend']}
The desired inverse dictionary would look like this:
inverse = { 'nisse': ['Testfil2.txt'], 'hue': ['Testfil2.txt', 'Testfil1.txt'], 'abe': ['Testfil2.txt', 'Testfil1.txt'], 'pind': ['Testfil2.txt'], 'tosse': ['Testfil1.txt'], 'svend': ['Testfil1.txt']}
Here's a Pythonic solution that addresses the issue with lists as values:
<code class="python">inverse = {} for k, v in index.items(): for x in v: inverse.setdefault(x, []).append(k)</code>
This solution iterates over the original dictionary, extracting each key-value pair and its elements. It uses the setdefault() method in the newly created inverse dictionary, which checks if the value (element from the list) is present as a key. If not, it creates a new key with an empty list as its value. If the key already exists, it appends the corresponding original key to the existing list.
By looping over all the elements in the original dictionary, this solution successfully creates the inverted dictionary with duplicate values merged and original keys as values.
The above is the detailed content of How to invert a dictionary with list values in Python?. For more information, please follow other related articles on the PHP Chinese website!