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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With