compare two dictionaries in python

To compare two dictionaries in Python, you can use the == operator. Here's an example:

main.py
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"a": 1, "b": 2, "c": 3}

if dict1 == dict2:
    print("The dictionaries are equal")
else:
    print("The dictionaries are not equal")
176 chars
8 lines

In this example, the dictionaries dict1 and dict2 contain the same key-value pairs. The == operator compares the content of the dictionaries, and if they are equal, it will print "The dictionaries are equal".

Keep in mind that the == operator checks for equality of both the keys and values in the dictionaries. If you want to check if two dictionaries have the same keys, but the order of the keys doesn't matter, you can use the set function. Here's an example:

main.py
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"c": 3, "b": 2, "a": 1}

if set(dict1.keys()) == set(dict2.keys()):
    print("The dictionaries have the same keys")
else:
    print("The dictionaries have different keys")
215 chars
8 lines

In this example, the set(dict1.keys()) and set(dict2.keys()) convert the keys of each dictionary into sets, and then the == operator is used to compare the sets. If the sets are equal, it will print "The dictionaries have the same keys".

related categories

gistlibby LogSnag