Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverting a dictionary with list values

So, I have this index as a dict.

index = {'Testfil2.txt': ['nisse', 'hue', 'abe', 'pind'], 'Testfil1.txt': ['hue', 'abe', 
'tosse', 'svend']}

I need to invert the index so it will be a dict with duplicates of values merged into one key with the 2 original keys as values, 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']

Yes, I typed the above by hand.

My textbook has this function for inverting dictionaries:

def invert_dict(d): 
    inverse = dict() 
    for key in d: 
        val = d[key] 
        if val not in inverse: 
            inverse[val] = [key] 
        else: 
            inverse[val].append(key) 
    return inverse

It works fine for simple key:value pairs

BUT, when I try that function with a dict that has lists as values such as my index I get this error message:

invert_dict(index)

Traceback (most recent call last):
    File "<pyshell#153>", line 1, in <module>
invert_dict(index)
    File "<pyshell#150>", line 5, in invert_dict
if val not in inverse:
TypeError: unhashable type: 'list'

I have searched for an hour looking for a solution, the book is no help, and I suspect that I can use tuples in some way, but I am not sure how. Any help?

like image 726
Vestergaardish Avatar asked Feb 18 '16 19:02

Vestergaardish


People also ask

Can dictionary have list as values?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.

How do I reverse a dictionary by value in python?

Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.

How do I change a dictionary to a list value?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.


1 Answers

My solution for reversing a dictionary. However, it creates a new dictionary new_dic:

new_dic = {}
for k,v in index.items():
    for x in v:
        new_dic.setdefault(x,[]).append(k)

Output :

{'tosse': ['Testfil1.txt'], 'nisse': ['Testfil2.txt'], 'svend': ['Testfil1.txt'], 'abe': ['Testfil1.txt', 'Testfil2.txt'], 'pind': ['Testfil2.txt'], 'hue': ['Testfil1.txt', 'Testfil2.txt']}
like image 119
ᴀʀᴍᴀɴ Avatar answered Nov 02 '22 19:11

ᴀʀᴍᴀɴ