You may also like ☞ Updating Dictionary in Python 3.9
Data structures are crucial parts of any programming language. In order to create robust and well-performing products, one must know the data structures very well.
In this post, we will work on an important data structure of Python programming language and that is Dictionary.
Dictionary is an unordered collection of key-value pairs. Each entry has a key and value. A dictionary can be considered as a list with special index.
The keys must be unique and immutable. So we can use strings, numbers (int or float), or tuples as keys. Values can be of any type.
Consider a case where we need to store grades of students. We can either store them in a dictionary or a list.
(image by author)
Using a dictionary allows us to access the grade of each student by providing the name of the student (key). On the other hand, to be able to access the grade of a particular student, we need an additional list.
The new list contains the names of the students and has the exact same order as the grades list.
(image by author)
Thus, a dictionary is a better choice than a list for such cases.
After this short introduction, let’s start on examples to dive deep into dictionaries. The examples will cover the features of dictionaries as well as the functions and methods to operate on them.
We can create a dictionary by providing 0 or more key value pairs between curly braces.
empty_dict = {}
grades = {'John':'A', 'Emily':'A+', 'Betty':'B', 'Mike':'C', 'Ashley':'A'}
grades
{'Ashley': 'A', 'Betty': 'B', 'Emily': 'A+', 'John': 'A', 'Mike': 'C'}
#python #machine-learning #data-science #artificial-intelligence