Search code examples
pythonfunctiondictionarycode-snippets

How to compare dictionaries with a function in Python 3+


I would like to compare dictionaries with a precise pattern inside a function. My final goal is to:

  • Incrementing by 3 the variable when 2 dictionaries have the same key and value
  • Decrementing by -1 the variable if the value is not the same
  • 0 if one pair of key/value is not present

for instance:

dict1 = {"EX1": "C", "EX2": "D", "EX4": "A", "EX5": "A"}
dict2 = {"EX1": "C", "EX2": "A", "EX3": "A", "EX4": "A", "EX5": "A"}

Expected output:

8

8 because: -The EX1 key has the same value in both dictionaries(3)

-The EX2 key hasn't the same value in both dictionaries(3-1=2)

-The EX3 key is not present in the dict1 so no operation(2)

-The EX4 key has the same value in both dictionaries(2+3=5)

-The EX5 key has the same value in both dictionaries(5+3=8)

I got from the internet those two snippets that I don't know how to convert into a function I don't know if these can help:

{k : dict1[k] for k in dict1 if k in rep_valid and dict1[k] == rep_valid[k]} #Get same items
{k : dict2[k] for k in set(dict2) - set(dict1)} #Get difference

Solution

  • You can use list comprehension to get the answer:

    dict1 = {"EX1": "C", "EX2": "D", "EX4": "A", "EX5": "A"}
    dict2 = {"EX1": "C", "EX2": "A", "EX3": "A", "EX4": "A", "EX5": "A"}
    
    # (count matching keys)*3 - (count not matching keys)
    ttl = len([k for k in dict1 if k in dict2 and dict1[k]==dict2[k]]) * 3 - len([k for k in dict1 if k in dict2 and dict1[k]!=dict2[k]])
    
    print(ttl)  # 8