How do I get my Python code to invert the ENTIRE dictionary and not just one section

I’m trying to master dictionaries, lists, and tuples right now.

I created a basic dictionary of Harry Potter names.
However, when I inverted it would only print the last house when it is inverted.
When trying to fix it, I realized even if I deleted something, it would still only ever print the last list in the dictionary.

#Character Reference Dictionary

Harry_Potter_Characters ={'Gryfindor':["Harry Potter",'Hermione Granger','Ron Weassley','Neville Longbottom'],
'Hufflepuff':["Nymphadora Tonks",'Newton Scamnder','Helga Hufflepuff','Cedric Diggory'],
'Slytherine':["Leta Lastrange",'Albus Potter','Regulas Black','Tom Riddle'],
'Ravenclaw':["Luna Lovegood",'Filius Flitwick','Sybill Trelawney','Myrtle Warren' ]}

print('Harry Potter Character Roster and House Dictionary',Harry_Potter_Characters)

#Modified inverse dictionary function

def invert_dict(d):
    inverse = dict()
    for key in d:
        val = d[key]
    for sub_key in val:

        if sub_key not in inverse:
             inverse[sub_key] = [key]
            inverse[sub_key]= inverse[sub_key].append(key)

    return inverse

print('Inverted dictionary:', invert_dict(Harry_Potter_Characters))


Harry Potter Character Roster and House Dictionary {'Gryfindor': ['Harry Potter', 'Hermione Granger', 'Ron Weassley', 'Neville Longbottom'], 'Hufflepuff': ['Nymphadora Tonks', 'Newton Scamnder', 'Helga Hufflepuff', 'Cedric Diggory'], 'Slytherine': ['Leta Lastrange', 'Albus Potter', 'Regulas Black', 'Tom Riddle'], 'Ravenclaw': ['Luna Lovegood', 'Filius Flitwick', 'Sybill Trelawney', 'Myrtle Warren']}

Inverted dictionary: {'Luna Lovegood': ['Ravenclaw'], 'Filius Flitwick': ['Ravenclaw'], 'Sybill Trelawney': ['Ravenclaw'], 'Myrtle Warren': ['Ravenclaw']}

>Solution :

This is how I would write it:

def invert_dict(d):
    inverse = {}
    for house, names in d.items():
        for name in names:
            inverse[name] = house
    return inverse

Leave a Reply