To compare two dictionaries in Python, you can use the ==
operator. Here's an example:
main.py176 chars8 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.py215 chars8 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".
gistlibby LogSnag