Dictionaries are ordered collection of items in which each item has a key : value pair. The key and value can be retrieved.
Dictionaries can be created by using curly brackets or by using the dict( ) constructor. The following program shows curly braces and dict( ) constructor to create a dictionary.
The number of items in a dictionary can be found by using the len( ) function. Following program shows the use of len( ) function to determine the number of items.
The keys( ) and values( ) method returns all the keys and values of the dictionary. The following program shows the use of keys( ) and values( ) method to get keys and values of a dictionary.
A value can be added to the dictionary by using a new key and giving a value to it. The following program shows addition of a key and value. If the key is already present then it gets updated with the new value.
Dictionary values can be deleted by using the specific key and pop( ) method. Any random key and value pair can be deleted by using the popitem( ) method. Also any specified dictionary value can also be deleted by using the del keyword and key name.
All the dictionary elements can be removed by using the clear( ) method. The following program shows the use of pop( ), popitem( ), clear( ) method and del keyword.
A dictionary can contain several other dictionaries which itself has key-value pairs. Such dictionaries are called nested dictionaries. The following program shows a nested dictionary.