The Python Oracle

Python3: Comparing a specific pair of keys and values between two dictionaries

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3

--

Chapters
00:00 Python3: Comparing A Specific Pair Of Keys And Values Between Two Dictionaries
00:51 Answer 1 Score 2
01:19 Accepted Answer Score 3
01:54 Answer 3 Score 1
02:17 Answer 4 Score 1
02:32 Thank you

--

Full question
https://stackoverflow.com/questions/5269...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #dictionary

#avk47



ACCEPTED ANSWER

Score 3


You could merge the dicts on equal (key, value) pairs and then run subsequent checks against the merged dict.

>>> dictA = {1:'Y', 2:'E', 3:'E'}
>>> dictB = {1:'Y', 2:'A', 3:'W'}
>>> 
>>> merged = dict(dictA.items() & dictB.items())
>>> merged
{1: 'Y'}
>>> 
>>> 1 in merged
True
>>> 3 in merged
False

Creating merged is painless because the return values of dict.keys, dict.values and dict.items support the set interface with regards to operations such as union, intersection, etc.

Caveat: requires hashable values in your dicts. If you have unhashable values, create merged via

>>> b_items = dictB.items()
>>> merged = dict(pair for pair in dictA.items() if pair in b_items)



ANSWER 2

Score 2


First get the matching keys between the dictionaries, then use a dictionary comprehension to compare each of these matching keys.

matching_keys = dictA.keys() & dictB.keys()

>>> {k: dictA[k] == dictB[k] for k in matching_keys}
{1: True, 2: False, 3: False}

To just get the keys where the values match, use a list comprehension:

keys_with_matching_values = [k for k in matching_keys if dictA[k] == dictB[k]]
# Or: [k for k in dictA if k in dictA and dictA[k] == dictB[k]]

>>> keys_with_matching_values
[1]

Note that both methods are memory efficient, as one does not needlessly store the matching values in the dictionaries.




ANSWER 3

Score 1


for key in dictA
    i = 0
    if key in dictA:
        word = dictA[0][i]
        if dictA[0][i] == dictB[0][0]:
            print(word + 'matches dict 0')
        if dictA[0][i] == dictB[0][1]:
            print(word + 'matches dict 1')
        if dictA[0][i] == dictB[0][2]:
            print(word + 'matches dict 2')
            i += 1

I wrote this really quick on the shuttle from work, its sloppy and I could make a loop for dictB. But this should work for automating the process of finding the word. (But may not work, because I wrote it quick)




ANSWER 4

Score 1


You could just do what you mentioned in a list comprehension

print([True if dicta[k] == dictb[k] else False for k in dicta])
# [True, False, False]

Expanded

for k in dicta:
    if dicta[k] == dictb[k]:
        print(True)
    else:
        print(False)