How to find keys in second dictionary which has different value compare to first dictionary
Question:
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'}
Answers:
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'}
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'}
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())
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'}
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'}
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'}
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())