Home > Backend Development > Python Tutorial > How Can I Invert a Python Dictionary with List Values?

How Can I Invert a Python Dictionary with List Values?

Mary-Kate Olsen
Release: 2024-10-31 05:55:01
Original
530 people have browsed it

How Can I Invert a Python Dictionary with List Values?

Inverting a Dictionary with List Values: A Comprehensive Solution

In the domain of Python programming, dictionaries are indispensable structures for storing data with key-value pairs. Occasionally, the need arises to invert a dictionary, particularly when the values are lists. This task presents challenges due to the unhashable nature of lists. However, there exists a straightforward solution to overcome this obstacle.

To achieve the inversion of a dictionary with list values, one can utilize the following snippet:

<code class="python">inverse = {}
for k,v in index.items():
    for x in v:
        inverse.setdefault(x, []).append(k)</code>
Copy after login

In this approach, the outer loop iterates through the keys and values of the original dictionary. For each value (which is a list), the inner loop iterates through each element of that list. For each element encountered, the inverse dictionary's behavior is determined by the following logic:

  • If the element (x) already exists as a key in the inverse dictionary, the key from the original dictionary (k) is appended to the corresponding value list.
  • If the element does not exist as a key yet, a new key is created with an empty list as the value, and the key from the original dictionary is appended to this new list.

This process effectively inverts the original dictionary, with the values (original keys) becoming keys, and the keys (original values) transformed into lists of the keys from which they originated. The resulting inverse dictionary contains the desired format.

The above is the detailed content of How Can I Invert a Python Dictionary with List Values?. 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