Reputation: 11
I have the following dictionaries:
movies = {"Fences": "Viola Davis", "Hick": "Blake Lively",
"The Hunger Games": "Jennifer Lawrence"}
and
tvshows = {"How to Get Away with Murder": "Viola Davis",
"Gossip Girl": "Blake Lively",
"The Office": "Steve Carrell"}
and I want as a result of these two the next dictionary where if a value is repeated in movies and tvshows must appear as follows :
{"Viola Davis": ["Fences", "How to Get Away with Murder"],
"Steve Carrell": ["The Office"], "Jennifer Lawrence":
["The Hunger Games"], "Blake Lively": ["Hick",
"Gossip Girl"]}
My code until now is:
tv_movies = { actor : [ program for program, actor in tvshows.items() if actor == actor ] for movie, actor in movies.items() }
but I get the following output:
print(tv_movies)
{'Viola Davis': ['The Office', 'How to Get Away with Murder', 'Gossip Girl'], 'Jennifer Lawrence': ['The Office', 'How to Get Away with Murder', 'Gossip Girl'], 'Blake Lively': ['The Office', 'How to Get Away with Murder', 'Gossip Girl']}
I´m stuck here, can you help me please?. Thank you very much
Upvotes: 0
Views: 64
Reputation: 179
ChainMap is supported from V3.3, so here is code that is compatible with python V2.x and 3.x
lis = [movies, tvshows] #make a list of dictionaries - movies, tvshows, etc..
d = {}
for element in lis:
for key, value in element.items():
if value not in d.keys():
d[value] = [key]
else:
d[value].append(key)
Upvotes: 0
Reputation: 1612
Maybe something like this?
from collections import ChainMap, defaultdict
d = defaultdict(list)
for title, actor in ChainMap(movies, tvshows).items():
d[actor].append(title)
Upvotes: 2