Sometimes, we want to compare two dictionaries and checking how many (key, value) pairs are equal with Python.
In this article, we’ll look at how to compare two dictionaries and checking how many (key, value) pairs are equal with Python.
How to compare two dictionaries and checking how many (key, value) pairs are equal with Python?
To compare two dictionaries and checking how many (key, value) pairs are equal with Python, we can use dict comprehension.
For instance, we write
shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
print(len(shared_items))
to get the values in dict x
if they’re key k
is in dict y
and x[k]
is equal to y[k]
.
And then we check the length of the shared_items
dict to see which items are the same in both dicts x
and y
.
Conclusion
To compare two dictionaries and checking how many (key, value) pairs are equal with Python, we can use dict comprehension.