在Python中创建另两个字典

2024-04-28 12:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下列词典:

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':[“办公室”,“如何逃脱谋杀”,“绯闻女孩”],“Jennifer Lawrence':[“办公室”,“如何逃脱谋杀”,“绯闻女孩”],“Blake Lively':[“办公室”,“如何逃脱谋杀”,“绯闻女孩”]}

我困在这里了,你能帮帮我吗?。非常感谢


Tags: themoviesactor办公室blake女孩livelydavis
2条回答

ChainMap在V3.3中受支持,因此下面是与PythonV2.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)

也许是这样的?你知道吗

from collections import ChainMap, defaultdict
d = defaultdict(list)
for title, actor in ChainMap(movies, tvshows).items():
    d[actor].append(title)

相关问题 更多 >