Dictionaries 101 – A Super Guide for a dictionaries in Python for Absolute Beginners

Shrish Last Updated : 01 Jul, 2021
7 min read

This article was published as a part of the Data Science Blogathon

Introduction

Dictionary Whenever I heard those words, I imagine of this

dictionaries in python oxford
Oxford Dictionary Image

What makes “dictionary” a “dictionary”. Well if you happened to use a dictionary and I am sure many of you had or using a dictionary now as well, if we see a dictionary for the very first time, the first thing that appears to us is its size. It is huge in size and there is no other way to phrase this.

However, if we opened the same dictionary we see a structure where all words are clubbed under one particular alphabet For example. all words starting with the alphabet “A” are clubbed under “A” like that.

Now imagine a situation. Let’s say you have put a dictionary on a table and out of nowhere, a huge Python snake appeared there.

dictionaries in python snake
Python Snake

Now this python let’s say swallow our dictionary. What will be your thought now while you are looking at this python?

It will something like “Python has dictionary now” :). That’s right, this is going to be our topic for this article. Now instead of dealing with Python(Snake), we will be dealing with Python(Programming Language) and we will be seeing everything about dictionary data type in Python. So let’s get started now with dictionaries in python.

Pre-Requisites

In this article, we will be getting ourselves familiar with dictionary data type in python. We will be seeing all the theoretical concepts and practical implementation of dictionaries in Python hence we need to have the certain setup ready on our laptop/pc.

1.Ananconda Distribution should be installed on the computer

2.Jupyter Notebook(Will be installed automatically once anaconda distribution is installed)

The choice of the operating system will be having no impact here as there is not going to be any difference in our code. Here I will be using Ubuntu 20.04.2 LTS. Likewise, you can use any OS of your choice as it is a personal preference.

What are dictionaries in Python?

As we have seen in the previous examples, real-life dictionaries are something that categorizes all the words starting with a particular alphabet under one alphabet. For example. All the words starting with the character “A” are characterized under the alphabet ‘A’. Now relating this to our programming world, in the dictionary all the words can be considered as values. These values are mapped to a particular character let’s called it a “key”.

For example.

Oxygen, Ore, Oracle all these words will be under the alphabet “O” in the dictionary. It means that all three words are values while the alphabet “O” is our key.

Similar is the concept of dictionaries in python. Dictionaries are basically key-value pairs where each value is associated with a respective key. Now let’s start with our practical implementation of dictionaries in python.

Creating dictionary in Python

In Python, dictionaries are indicated by { }(Two Curly Braces). So in order to create a dictionary in Python, all we need to do is to create those two braces and enclosed some values in there and viola, our dictionary is created in python.

Now here is the tricky part. Inside those two curly braces, we need to specify our key-value pairs which are separated by a colon “:”

Creating Dictionaries in Python:

my_dict = {1:100,2:200,3:300,4:400}

As in this code, you can see that we have created a dictionary and we have stored it in a variable named my_dict. Here we can see that there are two curly braces having key-value pairs separated by “:”.

Two important points to remember here:

1.Keys in the dictionary can be of any data type. For example. Strings, int, float

2.Values in the dictionary can be of any data type. For example. It can be int, float, strings, List and even other dictionaries are well.

You might have a query here. We have created a dictionary here but how can we verify whether it is really a dictionary or not?

Well, Python got us covered here. In python, there is a special function named “type()” using which we can verify what data type we are dealing with. So, let’s quickly check the data type of our my_dict variable.

Checking type of my_dict variable:

type(my_dict)

Output:

dict

From the result of the type() function, it is now confirmed that the variable that we are dealing with is indeed a dictionary one. Python has an internal coding system where each data type is represented with a shortcode. Here for dictionary, it is “dict”.

Accessing elements of a dictionary

We have created our dictionary in python. How about accessing a particular element from the dictionary?

The elements of the dictionary can be accessed based on keys associated with a respective value.

Accessing an element of a dictionary:

my_dict[2]

Output:

200

As we can see here in this code, we have accessed the value 200 from our dictionary based on key 2 since value 200 is mapped to key 2 in our dictionary.

Adding a new element to a dictionary

All data types in python can be classified into two main groups – Mutable and Immutable.

A data type is known as “Mutable” if and only if it can be modified at a later stage after its creation. For example. Lists, Dictionary, etc.

A data type is known as “Immutable” if and only if it can’t be modified at a later stage after its creation. For example. Strings

In our context, we are dealing with dictionaries which is a mutable data type meaning we can modify the contents of the dictionary. So let’s add a new element to the dictionary.

Adding a new element to a dictionary:

my_dict[5] = 500

As from this code, the syntax for adding a new element to a dictionary is pretty simple. Let’s see a brief explanation for the same. Here since we are going to add a new key in our dictionary which is 5 in this case.

We have mentioned this key in [ ] brackets followed by an equal sign which is then followed by the value associated with that key.

This is the convention used for adding a new element in the dictionary in python,

Here 2 important points need to be remembered:

1.Keys to be added should always be enclosed in [ ]

2.Values to be added should be to the right side of an assignment operator.

Since we have now added a new key-value pair in our dictionary let’s check the content of our dictionary

Checking contents of our dictionary:

my_dict

Output:

{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}

From the above output, it is evident that our new key-value pair is added to the dictionary.

Updating value associated with a key in a dictionary

We have a dictionary now having 5 key-value pairs respectively. Let’s say we decided to update the value of a particular key in a dictionary. Let’s update the value 200 which is associated with key 2 to 1000.

Updating value of a key in dictionary:

my_dict[2] = 1000

As we can see here, the syntax remains the same even while updating the value of a key in a dictionary.

Here 2 important points need to be remembered:

1.In [ ] always specify the name of the key which is already existing in our dictionary

2.On the right side of an assignment operator, we need to specify the name of the value that we are going to update in our dictionary.

Now let’s check our dictionary again after this update

Checking dictionary after update :

my_dict

Output:

{1: 100, 2: 1000, 3: 300, 4: 400, 5: 500}

As we can see here, the value associated with key 2 has been successfully updated to 1000.

Accessing all keys in a dictionary

We have our dictionary created now. We have accessed a particular element of a dictionary as well as we have accessed a respective element from a dictionary. How about accessing all keys which are present in a dictionary.

Python has a built-in method for accessing all keys in a dictionary called “keys()”. So now let’s access all keys in our dictionary using the keys() method.

Accessing all keys from a dictionary:

my_dict.keys()

Output:

dict_keys([1, 2, 3, 4, 5])

As you can see here, the keys() method of dictionary object has returned each and every key present in our dictionary.

Here one important thing needs to be remembered. Since keys() is basically a method , it will always be associated with a dictionary object. So If we don’t have a dictionary object we cannot use this method as methods as dependent on their corresponding objects.

Accessing all values in a dictionary

 Let’s also access all values present in our dictionary. For this as well, python has a built-in method for this named “values()”.

Accessing all values from a dictionary:

my_dict.values()

Output:

dict_values([100, 1000, 300, 400, 500])

As you can see here, our values() method has returned all the values which are present in our dictionary object.

Accessing all Items in a dictionary

Up to this point, we have accessed all keys and values individually which are present in our dictionary. How about accessing both keys and values simultaneously. For this, Python has a built-in method by the name called “items()”. What this method does is, it will access all the keys and values which are present in our dictionary.

Accessing all items from a dictionary:

my_dict.items()

Output:

dict_items([(1, 100), (2, 1000), (3, 300), (4, 400), (5, 500)])

As we can see here, the items() method has returned both the keys and values which are present in our dictionary object.

PRO Tip

 Up to this point, we have seen the basics of dictionary in python which involves the following:

1.Creation of dictionary in Python

2.Adding element in the dictionary

3.Accessing all keys in a dictionary

4.Accessing all values in a dictionary

5.Accessing all items in a dictionary

Now if you happened to see python’s official documentation for dictionary data type, there are lots of operations that can be performed on dictionaries. There are so many methods out there for dictionaries that it is technically impossible to cover all of those in a single blog post or even remember those.

In Python, there exist a special function that allows us to check a list of methods that can be invoked on a particular object based on its data structure. In our case since, we know that our “my_dict” is a dictionary type object in python, let’s check the list of all the method which can be invoked on this object by using a bulti-in function called “dir()”

Getting the list of all methods for dictionary object using dir() method:

dir(my_dict)

Output:

['__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'items',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']

As you can see here, the dir() function has listed all the methods which can be used with our dictionary data type.

Well, that’s it. This is everything that you need to know about dictionary data types in Python.

Do let me know how do you feel about this article.

https://www.linkedin.com/in/shrish-mohadarkar-060209109/

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 

My name is Shrish. I have been working as a data scientist at EY. I love technology and during my free time, I try to use my skills to create something awesome in python so that it can be shared on the analyticsvidhya platform

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details