Dictionary in python comprises an unordered collection of data stored in a key: value format. Dictionary is also known as "Associative memories" or "Associative arrays". In a dictionary, the key must always be unique. Whereas the values can be repeated and can be of any data type. The key-value pair should be represented as "key: value" (: colon is a must). Shown below are some most used dictionary methods and are one of the most commonly asked interview questions.
For example, declaring a dictionary in python:
# Declaring a dictionary
dictionary = {}
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23}
print(type(dictionary))
<class 'dict'>
Dictionaries can be accessed by their index to get the value. To do this, all you have to do is just place the number or the name of the key inside the pair of square brackets along with the name of the dictionary.
# Accessing the elements in a dictionary
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23}
print(dictionary['Name'])
Tanu
print(dictionary['Sex'])
Male
If you try to access the key which is not declared in the dictionary then an exception would be raised indicating no results found:
dictionary['Height']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-42-038ad6c9b2d4> in <module>() ----> 1 dictionary['Height'] KeyError: 'Height'
Also, we can use the get() of the dictionary to get or access the values of the dictionary as seen below:
print(dictionary.get('Age'))
23
In python, there are four different ways or methods that can be used to remove an element from a dictionary. Those are pop, del, popitem and clear. The del is used to delete a key from a dictionary, the pop is used to remove a specific key from a dictionary, popitem is used to remove the key arbitrarily from a dictionary, and the clear is used to just clear or delete all the elements in the dictionary (as the name suggests).
# Removing the elements from a dictionary
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
# Deleting an element
del dictionary['Name']
print(dictionary)
{'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
# Popping an item
print(dictionary.popitem())
('Occupation', 'Student')
# Popping the value
print(dictionary.pop('Sex'))
Male
print(dictionary)
{'Age': 23, 'Height': 5.8}
# Clearing the entire dictionary
dictionary.clear()
print(dictionary)
{}
Using a for loop we can iterate through each key in a dictionary as shown below:
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
# Iterating through the values
for i in dictionary:
print(dictionary[i])
Tanu Male 23 5.8 Student
# Iterating through the keys
for i in dictionary:
print(i)
Name Sex Age Height Occupation
The all () in dictionary returns "True" if all keys of the dictionary are true (or if the dictionary is empty). If the keys in the dictionary are true or if the dictionary all method returns true or else it will return false.
dictionary = {0: "Tanu", 1: "Prabhu"}
print(dictionary)
{0: 'Tanu', 1: 'Prabhu'}
print(all(dictionary))
False
dictionary = {1: "Tanu", 1: "Prabhu"}
print(all(dictionary))
True
dictionary = {}
print(all(dictionary))
True
The any () in dictionary return "True" if any key of the dictionary is true. If the dictionary is empty, returns "False".
dictionary = {0: "Tanu", 1: "Prabhu"}
print(dictionary)
{0: 'Tanu', 1: 'Prabhu'}
print(any(dictionary))
True
dictionary = {0: "Tanu", 0: "Prabhu"}
print(any(dictionary))
False
# 0 is False
dictionary = {0: "Tanu"}
print(any(dictionary))
False
The length () method in the dictionary returns the length of the dictionary (obviously). It returns the number of items of the dictionary.
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(len(dictionary))
5
The Sorted() method in dictionary returns a new sorted list of keys in the dictionary.
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
# Sorting in a ascending order
print(sorted(dictionary))
['Age', 'Height', 'Name', 'Occupation', 'Sex']
# Sorting in a descending order
print(sorted(dictionary, reverse = True))
['Sex', 'Occupation', 'Name', 'Height', 'Age']
The sorted() method accepts a reverse parameter as an optional argument.
As the name suggests the copy method in dictionary returns a copy of the dictionary.
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
dictionary1 = {}
print(dictionary1)
{}
dictionary1 = dictionary.copy()
print(dictionary1)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
Python dictionary method key() returns a list of all the available keys in the dictionary.
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary.keys())
dict_keys(['Name', 'Sex', 'Age', 'Height', 'Occupation'])
Python dictionary method values() returns a list of all the values available in a given dictionary.
dictionary = {'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary)
{'Name': 'Tanu', 'Sex': 'Male', 'Age': 23, 'Height': 5.8, 'Occupation': 'Student'}
print(dictionary.values())
dict_values(['Tanu', 'Male', 23, 5.8, 'Student'])
Hence above are the very important techniques or functions of Dictionary in Python. Some of the examples were referred from Python Dictionary. I have written this tutorial in a simple way such that everybody can understand and master the concepts of Dictionaries in Python without prior programming knowledge or experience. If you guys have some doubts in the code, the comment section is all yours. Thank you have a good day.