What is Python dictionary?
The dictionary is a data type in Python that is used to store data in key/value pairs.
If you have worked in other languages like PHP, you have worked with associative arrays; the dictionary is like that.
A dictionary can be created as follows:
- In the above example, the telephone_dir is the dictionary name.
- The names Mike, and Haynes are keys, and numbers 1234 and 4567 are their respective values.
- Each key/value pair is separated by a comma.
- While key and value are separated by a colon (:).
- The keys in the dictionary act as an index that is unlike sequences, for example, lists or tuples where only numbers act as an index.
- The keys in dictionaries can be numbers or strings. Using the string as an index makes it quite useful in establishing the relationship with their respective values.
- The keys in a dictionary are unique.
See the following examples of creating, accessing, deleting, and using other methods related to dictionaries in Python.
An example of creating a dictionary
In this example, a dictionary is created with three elements. The dictionary name is tel_dir where the name will act as keys and telephone numbers as values:
The code for creating and displaying a dictionary:
tel_dir = {'Mike': 123445689,'Haynes': 45678910, 'Mina':635363636} print (tel_dir)
Output:
Accessing a specific element of a dictionary example
By giving the key of an element in square brackets, you may access the specific element of a dictionary. See this example:
The following code is used to access:
tel_dir = {'Mike': 123445689,'Haynes': 45678910, 'Mina':635363636} print ("The number of Mike is: ", tel_dir['Mike'])
Result:
Using a for loop to iterate through dictionary elements
In this example, a for loop is used for accessing and displaying the dictionary elements. The items() method is used to retrieve the key and related value at the same time, as shown in the example below:
The code:
tel_dir = {'Mike': 123445689,'Haynes': 45678910, 'Mina':635363636} for name, number in tel_dir.items(): print ("The number of %s = %d" % (name, number))
Output:
The number of Haynes = 45678910
The number of Mina = 635363636
You see, first, I created the same dictionary as in the above example.
After that, a for loop is used where items() method is used with the dictionary name. The key is assigned to the name while the value is to numbers, which are displayed by using the print function.
Getting total number of dictionary items example
You may use the len method to get the total number of elements in the specified dictionary. The following example demonstrates how you can use it:
This is how the length is taken by using len() method:
tel_dir = {'Mike': 123445689,'Haynes': 45678910, 'Mina':635363636} print ("Total length of dictionary = ", len(tel_dir))
Output of above code:
Getting keys of a dictionary by using keys method
By using the dictionary keys() method, you may get the keys of the specified dictionary. See an example below for accessing the same dictionary keys as used in above example:
The code:
tel_dir = {‘Mike’: 123445689,’Haynes’: 45678910, ‘Mina’:635363636}print (list(tel_dir.keys()))
Output:
As this reruns “list” of the keys in the given dictionary, the keys are enclosed in square brackets just like an ordinary list does.
Accessing only values example
Similarly, you may access only the values of given dictionary by using the values() method. See a demonstration below:
The code:
tel_dir = {'Mike': 123445689,'Haynes': 45678910, 'Mina':635363636} print (list(tel_dir.values()))
Output:
Just like the keys method, the values return the list of values, so enclosed in square brackets in the output.
An example of removing all dictionary elements
By using the clear() method, you may remove all elements of the specified dictionary. Just write the name of dictionary you want to remove elements for, as shown in the example below:
Python code:
tel_dir = {'Mike': 123445689,'Haynes': 45678910, 'Mina':635363636} print ("Dictionary before clear: ",tel_dir) tel_dir.clear() print ("Dictionary after clear method: ",tel_dir)
Output:
You can see, the second print function displayed an empty dictionary after executing the clear() Python method.
Deleting a specific dictionary item example
Not only you can remove all elements by using the clear method, but you may also remove specific elements by using the key in the del() method.
See the example below with the same dictionary that I have been using in the above examples:
The code for deleting a specific element:
tel_dir = {'Mike': 123445689,'Haynes': 45678910, 'Mina':635363636} print ("Dictionary before del(): ",tel_dir) del tel_dir['Haynes'] print ("Dictionary after del method: ",tel_dir)
Output:
Dictionary after del method: {‘Mike’: 123445689, ‘Mina’: 635363636}
You can see in the second row of output, the record of the Haynes does not exist.
An example of sorting a Python dictionary
You may use the sorted() method to sort the dictionary items. In this example, the same dictionary is used and its keys are displayed before and after using the sorted method:
The code for sorting:
tel_dir = {'Mike': 123445689,'Haynes': 45678910, 'Tine':635363636} print ("Dictionary keys before sorting(): ",list(tel_dir.keys())) print ("Dictionary keys after sorting(): ",sorted(tel_dir.keys()))
Output:
Creating dictionaries by dict() constructor
The dictionaries in Python can also be created by using the dict() constructor. It will build a dictionary from the sequences of key values pairs.
One of the benefits of using this is you may create dictionaries by using dict comprehension. I will show an example after this one, first have a look at simply creating a dictionary by dict() constructor:
The code:
tel_dir= dict([('Mike',123445689), ('Haynes', 45678910), ('Tina',635363636)]) print ("A dictionary by dict constructor: ",tel_dir)
Output:
An example of dict comprehension
In this example, dict comprehension is used for creating a dictionary.
The code:
a_dict = {x: x**3 for x in (3, 6, 9, 12, 15)} print ("The key value pairs in dict comprehension: ",a_dict)
Output:
You can see, that the keys are the items in the given sequence while values are the cube of each respective item. Similarly, you may set a formula there for creating a dictionary.