Dictionary in python is one of the most frequently used collection data type. It is represented by hey value pairs. Keys are indexed but values may not be. There are many python-built in functions that make using the dictionary very easy in various python programs. In this topic we will see the three in-built methods namely cmp(), len() and items().
cmp()
The method cmp() compares two dictionaries based on key and values. It is helpful in identifying duplicate dictionaries as well as doing a relational comparison among the dictionaries. It is a feature on only python2 and not available in python 3.
Syntax
cmp(dict1, dict2) Where dict1 and dict2 are the two input dictionaries.
In the below example we see pairs of dictionaries compared with each other. The result is 0 if they are equal. It is 1 if 1st dictionary has a higher value and -1 if the first dictionary has a lower value.
Example
dict1 = {'Place': 'Delhi', 'distance': 137}; dict2 = {'Place': 'Agra', 'distance': 41}; dict3 = {'Place': 'Bangaluru', 'distance': 1100}; dict4 = {'Place': 'Bangaluru', 'distance': 1100}; print "comparison Result : %d" % cmp (dict1, dict2) print "comparison Result : %d" % cmp (dict2, dict3) print "comparison Result : %d" % cmp (dict3, dict4)
Running the above code gives us the following result:
comparison Result : 1 comparison Result : -1 comparison Result : 0
len()
This method gives the total length of the dictionary which is equal to the number of items. An item is a key value pair.
Syntax
len(dict)
In the below example we see the length of dictionaries.
Example
dict1 = {'Place': 'Delhi', 'distance': 137}; dict2 = {'Place': 'Agra', 'distance': 41 ,'Temp': 25}; print("Length of dict1",len(dict1)) print("Length of dict2",len(dict2))
Running the above code gives us the following result −
Output
Length of dict1 2 Length of dict2 3
dict.items()
Sometimes we may need to print out the key value pairs of a dictionary as a list of tuple pairs. The length method gives this result.
Syntax
Dictionayname.items()
In the below example we see two dictionaries and get the items in each of them as a tuple pairs.
Example
dict1 = {'Place': 'Delhi', 'distance': 137}; dict2 = {'Place': 'Agra', 'distance': 41 ,'Temp': 25}; print(dict1.items()) print(dict2.items())
Running the above code gives us the following result −
Output
dict_items([('Place', 'Delhi'), ('distance', 137)]) dict_items([('Place', 'Agra'), ('distance', 41), ('Temp', 25)])