Anna Choi
Anna Choi

Reputation: 21

How to compare values of two different hash maps in python

Hi i'm trying to figure out how to compare the values of two different hash maps that I have.

hash1 = {'animals':['dogs','cats']}
hash2 = {'canine': ['dogs','wolves']}

From the example above, since the key canine in hash2 has a value 'dogs' matching with the key animals in hash1 which also has 'dogs', I want it to print out 'canine'.

I was able to do something like this when a key only have one value, but I need it to have a long list of values and if any of the values match, I want it to print out which key it had any matches with.

EDIT: I want it to print out 'canine' because for example if I had multiple keys in hash2

hash2 = {'canine':['dogs','wolves'],'domestic':['horse','rabbit']}

I would only want it to print out 'canine' because that's the one that matches, instead of printing out the entire hash2

EDIT 2: hash1 = {'animals':['dogs','cats']} hash2 = {'canine': ['dogs','wolves']}

for value in hash2.values():
    if value in hash1.values():
        #not sure how to write this so here's pseudocode
        print(hash2[key of matching value])

Upvotes: 1

Views: 2099

Answers (3)

causation
causation

Reputation: 146

Here is some code that I think will get you close to what you are looking for. Let me know if it helps.

hash1 = {'animals':['dogs','cats']}
hash2 = {'canine':['dogs','wolves'],'domestic':['horse','rabbit']}

for key, value in hash1.items():
    for key1, value1 in hash2.items():
        matches = set(value).intersection(set(value1))
        if matches:
            print(matches)
            print(key, key1)

Upvotes: 1

raviraja
raviraja

Reputation: 706

something like this?

for key_1,value_1 in hash1.items():
    for key_2,value_2 in hash2.items():
        if len([x for x in value_1 if x in value_2])>0:
            print(key_2)

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 61032

We can build a set that contains all the items from all the values of hash1. We can then check if there is any intersection between that set and each of the values of hash2.

from itertools import chain

hash1 = {'animals':['dogs','cats']}
hash2 = {'canine':['dogs','wolves'],'domestic':['horse','rabbit']}

hash1_values = set(chain.from_iterable(hash1.values())) 
# equivalent to set(x for it in hash1.values() for x in it)


for k, v in hash2.items():
    if any(item in hash1_values for item in v):
        print(k)

Upvotes: 1

Related Questions