Home  >  Article  >  Backend Development  >  How to invert a dictionary with list values in Python?

How to invert a dictionary with list values in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 04:42:28842browse

How to invert a dictionary with list values in Python?

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!

Statement:
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