Topics

Functions for Dictionary

Welcome to another tutorial, here you look at some important functions.

 

len() 

The len() function is used to get the number of elements stored in the dictionary or use to get the number of keys in a dictionary.

>>> print(len(myDictionary));

Output:

6

 

clear() 

This function can be used to empty a dictionary, which is quite different from the del keyword used to delete all elements of the dictionary for each key value.

>>>myDictionary.clear()
>>> print (myDictionary);

Output:

{}

 

values() 

In a case where you don't want to access the keys while displaying the value stored in the dictionaries, you can make use of the values() function, as it will show all the values stored in the dictionary.

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

Output:

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

 

keys() 

The keys() functions acts opposite to the values() function. It is used where there is a need to view only the keys for a dictionary.

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

Output:

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

 

items() 

You can use the items() method to display the keys and values with a representation, in which they are mapped.

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

Output:

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

 

__contains__ 

This function can be used to check if a particular key exists in the dictionary. Therefore, if the key is present it returns True, else False

>>> myDictionary = {'Key-1': 'Element-1', 'Key-2': 'Element-2', 'Key-3': 'Element-3', 'Key-4': 'Element-4'}
print(myDictionary.__contains__('Key-2'));

Output:

True

 

cmp(): 

This function comes to handle when you need to compare two dictionaries. The function, however, returns 3 possible values, which 1,0, or -1. The function is available for use in Python 2.x and not in Python 3.x. However, it can be easily defined in Python 3.x and then used. When the function is used, if you have the dictionaries to be equal, then it will return 0; but if the second one has greater elements than the first, it returns -1, and then 1 for the reverse. Check out the example below:

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

Output:

0

Since both are same, hence the output is 0. 

Let’s add an extra element to x and see what happens.

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

Output:

1

Now let’s compare y with x:

>>> cmp(y, x)

Output:

-1

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

Note: the cmp function is not supported in Python 3.x