Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find values that share the same keys in a dictionary?

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))
like image 375
Declan Avatar asked Dec 08 '25 08:12

Declan


1 Answers

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']
like image 88
Mike Müller Avatar answered Dec 09 '25 22:12

Mike Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!