The first thing that comes to mind when you hear about dictionaries is the Oxford Dictionary where you can look up the meanings of words. So, you can imagine how dictionaries work. A dictionary is a collection of words along with their definitions or explanations.
At a broader level, you could describe a dictionary as a mapping of words with their synonyms or meanings. Let's learn about Python dictionaries in detail.
The dictionary structure looks as shown below:
Dictionary is one data structure that is very useful because of the way in which it is defined. Let's take a look at a small example to understand this. Imagine we have employee data with the following attributes: employee id, name, age, designation. Now, let’s say you want to retrieve employee details based on employee id (since this is unique to each employee). How would you store the data?
E_id | Employee Information |
101 | Akash, 24, Content Strategist |
102 | Vishal, 30, Project Manager |
….. | ….. |
159 | Vikas, 18, Intern |
Let’s say you use a list or tuple here; it would simply be difficult. Let’s see how.
First, you should have a list where each element represents an employee, and this element should be iterable again since you have different values to represent every employee.
[[e_id1, name1, age1, designation1],[e_id2, name2, age2, designation2]...]
But would this serve the purpose? There is a problem here: e_id is unique and cannot be changed, or, in other words, it is an immutable entity. Let’s say we make this entire element a tuple:
[(e_id1, name1, age1, designation1),(e_id2,name2, age2, designation2)...]
Now, this would make name, age and designation immutable entities; instead, they should be mutable entities:
[(e_id1, [name1, age1, designation1]),(e_id2,[name2, age2, designation2])...]
Having arrived at this point, imagine how it is to retrieve information about a particular employee based on their employee id. To achieve this, you need to use the loops concepts in Python, but isn’t this whole thing difficult? Imagine how simple this would be if you used a dictionary here:
E = [ e_id1 : [name1, age1, designation1],e_id2 : [name2, age2, designation2],...]
Here, e_id is unique;
name, age and designation are mutable; and
simply using E[e_id1] will give employee e_id1’s information.