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']}
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]
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]
}