Home > Article > Backend Development > How to Invert a Dictionary with List Values?
Your goal is to invert a dictionary (index) with list values such that the resulting dictionary (inverse) has duplicate values merged into one key with the original keys as values.
The provided function, invert_dict, fails when encountering list values due to the unhashable nature of lists. To resolve this, consider the following solution:
<code class="python">inverse = {} for k, v in index.items(): for x in v: inverse.setdefault(x, []).append(k)</code>
This solution iterates through the original dictionary (index), accessing each key (k) and value (v). For each value in v (which is a list), it adds the associated key to a list in the inverse dictionary using the setdefault method. The method creates a new entry for each unique value in v and appends the key to the associated list.
As a result, the inverse dictionary will contain the desired inverted structure, with each value being a list of original keys where that value appears.
The above is the detailed content of How to Invert a Dictionary with List Values?. For more information, please follow other related articles on the PHP Chinese website!