1

I can use diff = set(dict2) - set(dict1) to know that the dict1 and dict2 are not equal but what I need is to find which KEY in dict2 has a different value than dict1

 dict1 = {'c1': 'Iran', 'c2': 'India', 'c3': 'Iraq', 'c4': 'Qatar'}
 dict2 = {'c1': 'Iran', 'c2': 'India', 'c3': 'Iraqs','c4': 'Qeter'}
 diff = set(dict2) - set(dict1)
 print(diff)

Basically what I want to get in return are {'c3', 'c4'}

halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125
  • 1
    Does this answer your question? [How to get the difference between two dictionaries in Python?](https://stackoverflow.com/questions/32815640/how-to-get-the-difference-between-two-dictionaries-in-python) – teedak8s Mar 20 '23 at 05:13

3 Answers3

1

You can do like this,

keys = set()
for key in dict1:
    if key in dict2 and dict1[key] != dict2[key]:
        keys.add(key)

print(keys)

output:

{'c3', 'c4'}
Ajeet Verma
  • 2,938
  • 3
  • 13
  • 24
1

You can do like below:

dict1 = {'c1': 'Iran', 'c2': 'India', 'c3': 'Iraq', 'c4': 'Qatar'}
dict2 = {'c1': 'Iran', 'c2': 'India', 'c3': 'Iraqs', 'c4': 'Qeter'}
diff = set(dict2.items())-set(dict1.items())
diff_dict = dict(diff)
print(diff_dict.keys())
Hetvi
  • 188
  • 6
0

Use for loop to check same key in different dict.

dict1 = {'c1': 'Iran', 'c2': 'India', 'c3': 'Iraq', 'c4': 'Qatar'}
dict2 = {'c1': 'Iran', 'c2': 'India', 'c3': 'Iraqs', 'c4': 'Qeter'}
diff = {k for k in dict2 if dict2[k] != dict1[k]}
print(diff)

Output:

{'c4', 'c3'}
Shuo
  • 1,512
  • 1
  • 3
  • 13