Home Python Python Dictionary: The Definitive Guide With Video Tutorial

Python Dictionary: The Definitive Guide With Video Tutorial

0

What does the word “python” mean? You would probably go and look at the English to your language’s dictionary which tells you exactly that.

Okay, so, let me pose this question to you: What do you think the meaning of a dictionary itself is? The meaning of a dictionary can also be found in the dictionary itself. The meaning of a dictionary is “a collection of words to their meanings”.

Hello Guys,

Welcome to this new article from technicalustad.com on one cool Python’s Built-in data type called “dictionary”. Before I dive into the article, I would like to introduce myself and the platform that I am using to write this article.

My name is Rahul Jha and I am writing this article on technicalustad.com which is an online platform for technical contents in both video and text-based format. You should probably check out some of the tutorials that have been uploaded so far on this platform.

Okay, that was enough talking and it is time to see some action with python and its dictionary.

Data Structure in Python

We need to understand the concept of data structure in python before we can start talking about the dictionary in python. Python, by default, offers many inbuilt data structures that can be used to accomplish many tasks.

Let us look at some of the data structures that are available in python and also see what tasks they make us accomplish.

List

The list is a special data structure just like many others which enables us to store a collection of items in python. Let us take an example to understand this concept.

Let us assume that we want to create a list of students. Then, we can easily do that by storing the names of the students on the list. Similarly, we can make lists for storing various different sorts of things. Like the marks of the students, the height of the students, etc.

Sets, Tuples, etc

Set and tuple are two more examples of data structures in python and there is one similarity between list and tuple or set.

The similarity is that both fundamentally solve the same task and the task is to enable the programmer with the ability to store multiple items. Be it List, Set, or tuple, all of these essentially solve the same task and the task is to store multiple entries/items.

One question might arise that “Why do we need different data structures for solving the same requirement?” 🤔

The answer is very simple and that lies in some of the differences that lie among them.

One thing must be clear that each of these is collections. Set is a collection of only unique items. A tuple is a collection of only immutable items. On the other hand with lists, we can be both non-unique items, and also lists can be mutable.

We won’t talk more about that in this article as it is for a python dictionary not on the difference between different data structures.

So, what is a python dictionary? 🤷‍♂️

Python dictionary is also a data structure in python just like List, Set, and Tuple. But, a dictionary is a different type of data structure when compared to a list, set, and tuple.

Unlike list (which is just a collection of items), a dictionary is a collection of key-value mapping. Just like in a language dictionary, we have words and then their corresponding meaning, in python we have key and then its values.

To explain the concepts really concretely, I would like to take an example where I want to store the following things about

  1. Age
  2. Gender
  3. Nationality
  4. Income
  5. Occupation
  6. Name

Now, assume two different worlds, with and without a dictionary.

Without a dictionary

Let us make two different lists. To store the labels and to store the actual values. Storing Labels is also important as we might have to remember otherwise that which value belongs to which label. So, here is how it will be accomplished.

Python Dictionary

Now, obviously, the above way of storing the labels and actual corresponding values does the job for us but it is not the ideal way of doing this.

There is a better and we will soon look at that but right now just talk about what is wrong with the above way of storing this:

  1. Here, to actually know the person for which values belong to, we need to look at the name which is corresponding to the last index. So, we don’t know right away who these values are.
  2. If the size of the values list grows larger, then it would be difficult to keep track of their corresponding labels.
  3. And the above representation simply does not look good and clean.

With dictionary

Let us see how we can store the same variables in a much more elegant fashion.

Okay, first before we break down the above structure, take a good look at the above dictionary. Don’t focus too much on the syntax but try to understand the common structure.

You will notice that the above structure is a structure that resembles an actual dictionary where we have some words (like “age”) and their corresponding meanings (like 20 for age). Also, notice that each pair of words and its meanings are separated by comma ( , ).

Also, one more thing to notice that each pair itself is separated by a colon ( : ).

So, we have a list of words (to the left of the colon known as “key” in python dictionary) – meaning (to the right of the colon known as “values” in python dictionary) pairs separated by a comma each pair itself is separated by a colon and this list is enclosed within curly braces ({  }).

I hope you have understood the syntax of the dictionary. To give a summary, it stores a list of key-value pairs in curly braces, and each pair is separated by a comma and each pair key-value is separated by a colon, key being on the left of the colon, and value being on the right of colon.

One of the nice things about a dictionary is that dictionary can store any data structure. We can store lists and even other dictionaries.

When we store a dictionary inside another dictionary, then the dictionary is called a nested dictionary.

Let us extend the previous example that we took. We created a dictionary called “sam” in which we stored many properties. Now, let us make such a dictionary for sam and peter.

Python Dictionary

Here, we have stored two dictionaries for sam and peter respectively inside this dictionary. The idea is just the same.

First, we have keys and values as names and corresponding dictionary, So, corresponding to a name, let us say, “sam”, we have a list of properties stored in another dictionary and then we have a list of properties stored in another dictionary as a value for the key “peter”.

Okay, now that we have studied, what is a dictionary and how does that work, now we will see various things that can be done with it.

How to access values using a specified key?

Let us take the example of the same nested dictionary that we have had in the previous section and let us see what are the things that we can do with it.

Let us first see how to access the value with a given key. Let us demonstrate this by accessing the dictionary corresponding to sam and peter:

Here, we have first written the name of the dictionary and then opened the square bracket and then specified which key we would like to get the value of. We accessed dictionaries corresponding to both sam and peter. Now, since the resulting data structure is also a dictionary, we can index it further.

Let us think of a scenario where I am interested in the occupation of both sam and peter. How might I be able to accomplish that?

It is actually quite easy because the result of the above operation is just giving me yet another dictionary, we can just further out this indexing process.

Let us do that and access the occupation of both sam and peter.

I hope you are able to understand the above piece of code. We just index the nested dictionary by using nested indexing. First, we got access to the dictionary corresponding to the sam and then we further index using the key occupation. Finally, we have the value of “Business”.

A similar procedure resulted in “Freelance” for the occupation of the peter.

So, with this, I stop this discussion on how to index (or extract the value using key).

Getting the list of keys and values

Suppose a situation where your dictionary is becoming really long and printing that on an IDLE console is probably not a good idea. So, what can be done? You could print just a few keys or values.

How can this be done? This can be done by first calling the keys or values method on the dictionary, then printing just a few of those values.

Let us first look at how to print the keys and values of the dictionary using the methods keys() and values().

Python Dictionary

Note here that we have been using the same dictionary that we have started with. So, this dictionary has two keys “sam” and “peter”. It is natural that it will have two values as well as corresponding to each of the keys.

Let us take one more example in which we first make a new dictionary and then use the methods “values” and “keys” on the dictionary to extract the keys and their corresponding values from those dictionaries.

I hope this small discussion on how to extract the keys and values from the dictionary makes sense.

Looping with dictionary

If we just look at the way the dictionary is stored, it is also a collection. But unlike the list, it is a collection of key-value pairs. Now, what happens when we loop through a dictionary.

Let us have a look at what happens without actually looking at any theory…

Okay, first we declared a dictionary, and then we just looped through the dictionary. The result is that all keys of the dictionary are printed sequentially. So, by default, if we loop through the dictionary, then what we get is a list of keys.

Now, using the keys, we can also get access to the corresponding values. Let us see what that might look like.

Here, in the second loop, we defined the looping variable as key and then used that to access the value of the dictionary corresponding to the current key.

Okay. We understand how to loop through the keys and values. But the above two methods are not quite self-evident.

So, if we need to explicitly tell the user that we are looping through keys and values, what we can do is we can call the keys and values method of the dictionary and then loop through that, and in this way we will be very explicit. Let us look at how to do that.

The above example clearly shows us how to loop through the list of keys and print it.

Then, in a similar manner, we can loop through the values by calling the values method of the dictionary. I leave this to the reader as an exercise.

I have to discuss one more thing before moving onto the next section. So, there is a method called items() which can be used to get both keys and values at the same time. Let us first see how it works and then we will look at the mechanics of it.

Python Dictionary

So, here we are first calling the items method on a dictionary which returns a list (collection) of tuples where each tuple is just having two items (the first one is key and the second one is value). Then, we are printing keys and values using python print.

You may like to read Python For Loop: The Definitive Guide With Video Tutorial.

An alternative method of accessing the value

Earlier, we looked at how we can use square brackets to get a particular value of the dictionary. We just need to specify the key inside the square bracket and then we are good to go.

But there is an alternative way of accessing the value and that is by calling the get method of the dictionary. Using this method, we can pass the key that we are interested in and then get the value corresponding to that key.

Let us look at an example of the “get” method with a dictionary.

Notice here, you need to pay attention to get the point that I want to convey. First, we used the “get” method with the keys “name” and “Last”. We got the correct result but while using it with a misspelled “last” key, we got nothing.

You might expect to get an error but the “get” statement works like that only. When calling it with some key which is not present in the dictionary, it won’t give you any output.

Adding items in the dictionary

So far we have looked at many different examples of dictionaries where we demonstrated many different concepts related to dictionaries. We saw how to loop through them, how to access its items etc.

What if we want to add more items in an already existing dictionary. We saw earlier how to access values using square brackets. Now, with this same method, we can set a key that does not exist yet with some value of our choice.

Let us first look at how it works and then we will understand the mechanics of it.

First, we defined a new dictionary and then we used the square bracket method to get access to a variable name called “favorite color” but if you notice the dictionary, there is no such key called “favorite color”, so we assigned this new key to the color “Blue” which is now part of the dictionary. We can see that after seeing the print statement.

So, this is the method of assigning a new key with a value.

If statement with Dictionary

How can we test whether a particular key exists in a dictionary or not? To test this, we can use the “in” keyword in python. We just need to say something like “name in dict1”, then it will result in True or False.

Let us first look at how it works and then we will understand why something like this might be desired.

So, the statement that we have just used is an example “in” keyword and it is quite self-explanatory.

Assume that we have a long dictionary with a number of keys greater than or equal to 1000.

In such a case, it might happen that accidentally we may override an existing key-value while setting a new key. So, it would be better in this case to first test whether that key (which we want to test already exists or not). It can be easily done by the “in” keyword.

Let us look at a practical example of that.

In the above example, notice the “if else” block, we have first tested whether the key “new” is already there in the dictionary or not, if it is, we pass and do nothing while if is not, we set the value of the new keyword to new.

It is one of the handy ways of setting many values at one time and also testing them whether they exist or not.

Some useful things that we can do dictionaries

del keyword in python

How can I delete a specific item from the dictionary? It is quite easy with the “del” keyword in python.

The following example demonstrates how to delete the “age” keyword from the dictionary:

Python Dictionary

Notice the way the keyword “del” has been used. First, we write the name of the keyword “del” and then access that item we want to delete.

Pop the last item

There is a method called “popitem” in a dictionary, with which we can delete the last key-value pair from the dictionary.

When we invoke this method, it returns the last key and value pair as a tuple that the method deleted, and then the last item will be no longer present in the dictionary.

The following example demonstrates the point.

Notice in the above example, we first had a dictionary with the nationality as Indian as the last entry in the dictionary and after calling the “popitem” method on it, we get a tuple which just holds the key value pair of the item it deleted.

Then, when we print the dictionary again, we see that there is no entry such as nationality present in the dictionary.

Get a new Copy of the dictionary

To get a new copy of the dictionary, we can just call the copy method of the dictionary and a new copy will be created and that can then be set to a new variable. This method is demonstrated below.

Clear the entire dictionary

To clear the entire dictionary, we can call the clear method of the dictionary which empties the entire dictionary.

String and printable version of the dictionary

The “str” method of the dictionary will give us a string representation of the diction.

Here is the practical demonstration of all the three methods we just discussed.

First, we made a copy variable that stores the copy of the dictionary by calling the copy method of the dictionary. Then, we used str( )  function to produce the printable version of the dictionary.

Finally, we called the clear method on the dictionary and the result of that is that we have an empty dictionary.

Okay, so, With this last discussion on various additional functions or methods that are available with a dictionary in python, I will stop this article right here and I hope you have been able to understand everything that we discussed in this article.

At this point in time, I will encourage every one of you to explore more about dictionaries and one of the best things that you can do is to actually go through each code example from this article, and run that on your system and make sure you understand everything about that.

Now it’s time to explore our Python Dictionary video tutorial guide.

Thank you. 🙂