Python script to compare the keys of 2 dictionaries and if equal print value of the key of 2nd dictionary

0

I have 2 dictionaries for example:

dict = {1 : a, 2 : b, 3 : c, 4 : d} 
dict1= {5 : z, 1 : y, 6 : x, 3 : u}

I need to compare the keys of 2 dictionaries and if they are equal, I have to print the corresponding value of the 2nd dictionary's key. For example, both dictionaries have 1 and 3 as their key so I have to print their corresponding value in the 2nd dictionary i.e. it should print y and u. How to write the python script for this? I have tried something like:

def compare(dictOne,dictTwo):
    for keyOne in dictOne:
        for keyTwo in dictTwo:
            if keyOne == keyTwo:
                print(dictTwo[keyTwo])

But I am not getting the output.

user999

Posted 2015-11-25T10:45:25.337

Reputation: 1

Answers

2

This would be better asked on StackOverflow.

Here is the most pythonic way of doing this:

d1 = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
d2 = {'z': 260, 'd': -12, 'r': 1, 'b': 0}

# Use a dictionary comprehension to collect d2 values of shared key
d3 = {key:d2[key] for key in d1 if key in d2}

This python code uses a dictionary comprehension to iterate through d1's keys and, if the key is in both d1 and d2, store the key in d3 with the value from d2.

Here is the result in the python interpreter:

>>> d1 = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
>>> d2 = {'z': 260, 'd': -12, 'r': 1, 'b': 0}
>>> d3 = {k:d2[k] for k in d1 if k in d2}
>>> d3
{'d': -12, 'b': 0}

Note: You don't need to call d1.keys(), but it is good practice. I intentionally did not call .keys().

Charles Addis

Posted 2015-11-25T10:45:25.337

Reputation: 121

0

I formatted your code correctly and tested and it worked for me. I'm not sure why you weren't seeing any output.

def compare(dictOne,dictTwo):
    for keyOne in dictOne:
        for keyTwo in dictTwo:
            if keyOne == keyTwo:
                print(dictTwo[keyTwo])

dict1 = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd'}
dict2= {5 : 'z', 1 : 'y', 6 : 'x', 3 : 'u'}
compare(dict1,dict2)

While not the most efficient code it does work.

For something more efficient I would suggest the same code that grawity provided:

def compare2(dictOne,dictTwo):
    for key in dictOne:
        if key in dictTwo:
            print(dictTwo[key])

JeHor

Posted 2015-11-25T10:45:25.337

Reputation: 1

-1

for key in dictTwo:
    if key in dictOne:
        print(key, "=", dictTwo[key])

user1686

Posted 2015-11-25T10:45:25.337

Reputation: 283 655

1While this may answer the question, it would be a better answer if you could provide some explanation why it does so. – DavidPostill – 2015-11-25T21:16:14.800