Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inverting dictionary in python

I have this dictionary

{'jackie chan': ('rush hour', 'rush hour 2'), 
 'crish tucker': ('rush hour', 'rush    hour 2')}

I want the inverse dictionary to be

{'rush hour': ('jackie chan', 'crish tucker'), 
 'rush hour 2': ('jackie chan', 'crish tucker')}

I already got the function to inverse but it doesn't look like the second dictionary

def invert_actor_dict(actor_dict):
    movie_dict = {}
    for key,value in actor_dict.iteritems():

        for actor in value:
            if actor in movie_dict:
                movie_dict[actor].append(key)
            else:
                movie_dict[actor] = (key)
    return movie_dict
like image 636
Asdfg Adfg Avatar asked Nov 23 '11 17:11

Asdfg Adfg


People also ask

How do I reverse a dictionary order in Python?

Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.


1 Answers

You can easily do this with collections.defaultdict:

def invert_dict(d):
    inverted_dict = collections.defaultdict(set)
    for actor, movies in d.iteritems():
        for movie in movies:
            inverted_dict.add(actor)
    return inverted_dict
like image 173
rubik Avatar answered Nov 15 '22 07:11

rubik