gpt4 book ai didi

python - 如何在字典中查找共享相同键的值?

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:21 26 4
gpt4 key购买 nike

我希望输入为 actorsInCommon(movies, "Moneyball", "Oceans Eleven")

我希望输出为 ["Brad Pitt", "Joe Smith"]

movies = {"Moneyball": ["Brad Pitt", "Jonah Hill", "Joe Smith"], 
"Oceans Eleven": ["Brad Pitt", "Joe Smith", "George Clooney"]}

def find(key, dictionary):
for (k, value) in dictionary:
if key == k:
return value
return None

def actorsInCommon(dictionary, movie1, movie2):
movie1Cast = find(movie1, dictionary)
movie2Cast = find(movie2, dictionary)
return list(set(movie1Cast).intersection(movie2Cast))

最佳答案

movies = {"Moneyball": ["Brad Pitt", "Jonah Hill", "Joe Smith"], 
"Oceans Eleven": ["Brad Pitt", "Joe Smith", "George Clooney"]}

从两个字典中的值中获取创建的两个集合的交集。使用默认为空列表的 get()(如果使用,将转换为一个集合)用于缺少电影名称。转换为列表以匹配所需的输出:

def actorsInCommon(dictionary, movie1, movie2):
return list(set(dictionary.get(movie1, [])) & set(dictionary.get(movie2, [])))

>>> actorsInCommon(movies, "Moneyball", "Oceans Eleven")
['Brad Pitt', 'Joe Smith']

关于python - 如何在字典中查找共享相同键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36163153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com