I want input to be actorsInCommon(movies, "Moneyball", "Oceans Eleven")
I want output to be ["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"]}
Take the intersection of the two sets created form the values in both dictionaries. Use get() with a default of an empty list (that will be converted into a set if used) for missing movie names. Convert into a list to match the desired output:
def actorsInCommon(dictionary, movie1, movie2):
return list(set(dictionary.get(movie1, [])) & set(dictionary.get(movie2, [])))
>>> actorsInCommon(movies, "Moneyball", "Oceans Eleven")
['Brad Pitt', 'Joe Smith']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With