Signup/Sign In

Dictionary Functions in Python

Let's check out some important functions that are quite helpful when we are playing around with dictionaries in python.


As you might have already guessed, it gives the number of elements stored in the dictionary or you can say just the number of keys in it.

>>> print(len(myDictionary));



If we ever need to delete all elements of the dictionary using the del keyword, for each key value, that would be quite troublesome. Hence clear() function makes emptying a dictionary, a single line task.

>>> print (myDictionary);



Suppose you don't want to access the keys while displaying the value stored in the dictionaries, then values() function can be used. This function will show all the values stored in the dictionary.

>>> print (myDictionary.values());

{"Element-1", "Element-2", "Element-3", "Element-4", "Element-5"}


This function is opposite to the function values(). As the name suggests, in case you want to view only the keys for a dictionary, then you can use the keys() function.

>>>print  (myDictionary.keys());

{"Key-1", "Key-2", "Key-3", "Key-4", "Key-5"}


In case you want to display both, keys and values with a representation, where both are well mapped, then use the items() method.

>>> print (myDictionary.items());

{('Key-1': 'Element-1'), ('Key-2': 'Element-2'), ('Key-3': 'Element-3'), ('Key-4': 'Element-4'), ('Key-5': 'Element-5')}


To check if a particular key exists in the dictionary, this function can be used. If the key that you are looking for exists then it returns True, otherwise False.

>>> myDictionary = {'Key-1': 'Element-1', 'Key-2': 'Element-2', 'Key-3': 'Element-3', 'Key-4': 'Element-4'}



In case you ever need to compare two dictionaries, cmp() function can be used to do so. It can return 3 possible values, i.e., 1, 0 or -1. cmp() function was available in Python 2.x but is not available in Python 3.x but we can easily define this function and use it.If both dictionaries are equal, then 0. If second have greater elements than first, then -1 and 1 for the reverse. It can be used like

>>> x = {1: 1, 2:2, 3:3}
>>> y = {1:1, 2:2, 3:3}
>>> print (cmp(x, y))


Since both are same, hence the output is 0.

Now let's add one an extra element to x.

>>> x[4] = 4
>>> cmp(x, y)


Now that x is having more elements, hence the output is 1. Also, if we compare y with x, then

>>> cmp(y, x)


The output becomes -1, because y has less elements.

cmp is not supported in Python 3