Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)
print("")

#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]
        else:
            inverse[sub_key]= inverse[sub_key].append(key)

    return inverse


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

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading