mgz mgz - 9 months ago 94
Python Question

Inverting a dictionary

I'm trying to invert the dictionary below but I keep getting an error that says

builtins.TypeError: unhashable type: 'list'


input_dict = {
1: ['hi', 'there', 'fred'],
2: ['there', 'we', 'go'],
3: ['fred', 'was', 'there']}


Here's what I tried to do

def make_index(words_on_page):
"""Invert the dictionary"""

inverted = {}
for index, word in words_on_page.items():
if word in inverted:
inverted[word].append(index)
else:
inverted[word] = [index]


Can anyone please point out where I made a mistake?

Answer Source

You just have to iterate the words corresponding to the keys, like this

input_dict = {
    1: ['hi', 'there', 'fred'],
    2: ['there', 'we', 'go'],
    3: ['fred', 'was', 'there']
}


def make_index(words_on_page):
    """Invert the dictionary"""
    inverted = {}
    for index, words in words_on_page.items():
        for word in words:
            if word in inverted:
                inverted[word].append(index)
            else:
                inverted[word] = [index]
    return inverted

print(make_index(input_dict))

Result

{
 'fred': [1, 3],
 'go': [2],
 'hi': [1],
 'there': [1, 2, 3],
 'was': [3],
 'we': [2]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download