我有以下词典:
movies = {"Fences": "Viola Davis", "Hick": "Blake Lively",
"The Hunger Games": "Jennifer Lawrence"}
和
tvshows = {"How to Get Away with Murder": "Viola Davis",
"Gossip Girl": "Blake Lively",
"The Office": "Steve Carrell"}
我希望这两个词的结果是下一个词典,如果在电影和电视剧中重复一个值必须如下所示:
{"Viola Davis": ["Fences", "How to Get Away with Murder"],
"Steve Carrell": ["The Office"], "Jennifer Lawrence":
["The Hunger Games"], "Blake Lively": ["Hick",
"Gossip Girl"]}
我的代码到现在为止:
tv_movies = { actor : [ program for program, actor in tvshows.items() if actor == actor ] for movie, actor in movies.items() }
但我得到以下输出:
print(tv_movies)
{'Viola Davis':['The Office','如何摆脱谋杀','绯闻女孩'','Jennifer Lawrence':'''办公室','如何摆脱谋杀','绯闻女孩'],'布莱克活泼':['办公室','如何摆脱谋杀','绯闻女孩'}}
我被困在这里,你能帮帮我吗?非常感谢你
答案 0 :(得分:2)
也许是这样的?
from collections import ChainMap, defaultdict
d = defaultdict(list)
for title, actor in ChainMap(movies, tvshows).items():
d[actor].append(title)
答案 1 :(得分:0)
V3.3支持ChainMap,因此这里的代码与python V2.x和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)