我有一个字典设置为movie:{actors}。下面是这本字典的一个片段
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'}
}
我正在努力创建一本联合主演词典,这样每个演员都是关键,它的价值观就是它的一组搭档。
提前感谢您的帮助!:)
您可以使用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'}
也许这就是您想要的。
output = {}
for movie, actors in movie_dict.items():
for actor in actors:
if actor in output:
[output[actor].add(i) for i in actors if i != actor]
else:
output[actor] = set([i for i in actors if i != actor])
print(output)
输出
{'Brad Pitt': {'Anthony Hopkins',
'Diane Kruger',
'Dustin Hoffman',
'George Clooney',
'Julia Roberts',
'Kevin Bacon',
'Morgan Freeman'},
'Dustin Hoffman': {'Brad Pitt', 'Kevin Bacon'},
'Kevin Bacon': {'Brad Pitt', 'Dustin Hoffman'},
'Diane Kruger': {'Brad Pitt'},
'Anthony Hopkins': {'Brad Pitt'},
'Julia Roberts': {'Brad Pitt', 'George Clooney'},
'George Clooney': {'Brad Pitt', 'Julia Roberts'},
'Morgan Freeman': {'Brad Pitt'}}
def type_key():
Item_ = input("item key: ")
return Item_
def Type_val():
sett = set()
x = 1
while x:
sett.add(input("value: "))
x = 2
while x not in (0, 1):
x = int(input("0. break, 1. continue"))
return sett
def craet_dic():
dic = {}
x = 1
while x:
dic[type_key()] = Type_val()
x = 2
while x nit in (0, 1):
x = int(input("0. break, 1. continue: "
return dic
print(craet_dic())