Categories
Python Answers

How to compare two dictionaries and checking how many (key, value) pairs are equal with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *