Working with Dictionaries
Welcome, developers! Today, we are going to learn about dictionaries.
Just like real-life dictionaries, Python dictionaries use pairs of elements named keys and values. When we want to understand the meaning of a word in a regular dictionary, we use the word (that would be the ‘key’ in Python) to look up its explanation (the ‘value’ in Python).
Imagine a piece of paper where you write down your friends’ favorite foods. It might look something like this:
John: Pizza
Jean: Pasta
Oliver: Broccoli
In this example, ‘John’, ‘Jean’, and ‘Oliver’ would be the dictionary keys, while ‘Pizza’, ‘Pasta’, and ‘Broccoli’ would be the dictionary values.
We can define a Python dictionary like this:
friends_foods = {
'John': ‘Pizza’,
‘Jean’: ‘Pasta’,
‘Oliver’: ‘Broccoli’
}
Then, we can access the dictionary elements like this:
print(friends_foods['John'])
# prints out Pizza
As you will see, dictionaries are among Python’s most powerful data collection structures, allowing us to use data processing operations in Python that are similar to the ones used by the most powerful database platforms in the world.
Let’s see how we can build a simple and yet useful application that uses a dictionary to store, add, update and retrieve
information. We will create an application that manages student information.
The code in the image below defines the dictionary and shows us how easy it is to reference user information.
Type in the code in your preferred editor, and then use a few more lines of code to display the ages and grades for the rest of the students in our dictionary.
We can easily add another student using a single line of code:
students[‘Michael’] = {‘age’: 23, ‘grade’: ‘95’}
Then, we can easily access the new student’s data as well:
This isn’t a practical way of managing things when we are dealing with a large number of student records, though. What if we had to display all the information for all the students at once?
Fortunately, we can easily do that using a ‘for’ loop:
And this is what our application outputs:
What if we wanted to display the average grades? We can add all the student grades, and then we divide that number by the number of dictionary elements, which can be retrieved using the ‘len’ method.
This concludes our Python dictionaries tutorial. Now that we’ve laid out the basics, we will use this information in the next lesson to analyze a huge public domain data source and create a histogram out of it.