Python 3 – Dictionary cmp() Method
The cmp()
method in Python is a built-in function that is used to compare two objects. It returns “-1” if the first object is smaller, “0” if both objects are equal, and “1” if the first object is larger. However, the method is removed from Python 3.0 and onwards.
But, in Python 2, cmp()
method is a very useful function in generating dictionaries. With Python 3, the dictionary can be sorted by providing the keys, values or items as a sorted list but it doesn’t have an equivalent function to cmp()
method.
Let’s have a closer look at how the cmp()
method can be used with dictionaries in Python 2.
Syntax
cmp(dict1, dict2)
Parameters
The cmp()
method accepts two dictionary objects as parameters.
dict1
: This is the first dictionary that we want to compare with the second dictionary.dict2
: This is the second dictionary that we want to compare with the first dictionary.
Return Value
The cmp()
method returns an integer value of “-1”, “0” or “1” according to the comparison result.
-1
: If the first dictionary is smaller than the second one.0
: If the two dictionaries have the same key-value pair.1
: If the first dictionary is larger than the second one.
Example
fruits1 = {"Orange": 4, "Mango": 6, "Apple": 2, "Banana": 5, "Kiwi": 1, "Pomegranate": 3}
fruits2 = {"Peach": 3, "Mango": 5, "Apple": 2, "Banana": 6, "Kiwi": 1, "Pomegranate": 4}
print("Dictionary Keys Comparison: ", cmp(fruits1, fruits2))
Output:
('Dictionary Keys Comparison: ', -1)
In the above example, two dictionaries fruits1
and fruits2
are defined by key-value pairs. Then, the cmp()
method is used to compare these two dictionaries. It returns “-1” as fruits1
dictionary has fewer keys than the fruits2
dictionary.
Conclusion
In summary, the cmp()
method was an important method in the dictionary functionality of Python 2. But, with Python 3, the method is no longer available, and we can instead use the sorted()
function for sorting Python dictionaries.