I have a dictionary set up as movie: {actors}. Below is a snippet of this dictionary
movie_dict = {
'Sleepers': {'Brad Pitt', 'Kevin Bacon', 'Dustin Hoffman'},
'Troy': {'Brad Pitt', 'Diane Kruger'},
'Meet Joe Black': {'Brad Pitt', 'Anthony Hopkins'},
'Oceans Eleven': {'Julia Roberts', 'Brad Pitt', 'George Clooney'},
'Seven': {'Brad Pitt', 'Morgan Freeman'}
}
I am trying to create a dictionary of Co-Stars so that every actor is a key, and its values are a set of its costars.
Thanks in advance for any help! 🙂
>Solution :
You could use collections.defaultdict:
>>> from collections import defaultdict
>>> movie_dict = {
... 'Sleepers': {'Brad Pitt', 'Kevin Bacon', 'Dustin Hoffman'},
... 'Troy': {'Brad Pitt', 'Diane Kruger'},
... 'Meet Joe Black': {'Brad Pitt', 'Anthony Hopkins'},
... 'Oceans Eleven': {'Julia Roberts', 'Brad Pitt', 'George Clooney'},
... 'Seven': {'Brad Pitt', 'Morgan Freeman'}
... }
>>> costars = defaultdict(set)
>>> for actors in movie_dict.values():
... for actor in actors:
... costars[actor] |= actors - {actor}
...
>>> for actor, actors_costars in costars.items():
... print(f'{actor}: {actors_costars}')
...
Brad Pitt: {'Anthony Hopkins', 'George Clooney', 'Julia Roberts', 'Diane Kruger', 'Dustin Hoffman', 'Kevin Bacon', 'Morgan Freeman'}
Kevin Bacon: {'Brad Pitt', 'Dustin Hoffman'}
Dustin Hoffman: {'Brad Pitt', 'Kevin Bacon'}
Diane Kruger: {'Brad Pitt'}
Anthony Hopkins: {'Brad Pitt'}
George Clooney: {'Julia Roberts', 'Brad Pitt'}
Julia Roberts: {'George Clooney', 'Brad Pitt'}
Morgan Freeman: {'Brad Pitt'}