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

Creating a dictionary from another dictionary where keys' = (values in previous dictionary) and value' = (shared values in previous dictionary)

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! 🙂

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

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