How to invert a dictionary with list values in Python?

Patricia Arquette
Release: 2024-10-30 04:42:28
Original
864 people have browsed it

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']}
Copy after login

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']}
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!