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

Time:11-08

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:

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

CodePudding user response:

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

CodePudding user response:

Indentation issue in the inner loop. It runs only once for the last val.

inverse = dict()
for key in d:
    val = d[key]
for sub_key in val: ## This has wrong indent

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

return inverse

You also don't need to check for "not in inverse" or "append if it's present" if it's guaranteed that one person can only belong to one house. However, for the general case where a person could belong to multiple houses (ex. inverting which banks does a person have an account in), you'll need this logic.

CodePudding user response:

Just need to indent the second for loop in to the first.
Also you can use d.items() to save you a step.

def invert_dict(d):
    inverse = dict()
    for key, val in d.items():
        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
  • Related