How do I compare dicts in Python with examples?

In Python, comparing dictionaries can be done using the equality operator (==) which checks if the dictionaries have the same key-value pairs. Additionally, you can also compare them using the cmp() function in Python 2 or manually by iterating over keys and values in Python 3. Below, we provide examples that illustrate how to compare dictionaries in various ways.

# Example of comparing dictionaries in Python # Creating two dictionaries dict1 = {'a': 1, 'b': 2, 'c': 3} dict2 = {'a': 1, 'b': 2, 'c': 3} dict3 = {'a': 1, 'b': 2} # Using the equality operator print(dict1 == dict2) # Output: True print(dict1 == dict3) # Output: False # Checking keys and values separately def compare_dicts(d1, d2): return d1.keys() == d2.keys() and all(d1[k] == d2[k] for k in d1) print(compare_dicts(dict1, dict2)) # Output: True print(compare_dicts(dict1, dict3)) # Output: False

compare dicts Python dictionaries dictionary comparison Python programming