Python Dictionary( Part I )

Vivek Nikam and Abhay Chaudhari
3 min readJun 18, 2021

smart and simple

Photo by Albuu Design de Álbuns on Unsplash

Dictionary is one of the most important data structure in python.

Dictionary is a mutable object which means we can add and delete values from it.

It is a collection of key:value pairs inside curly braces ( { } ).

d1 = { key1:value1, key2:value2, key3:value3 }

this is how we can create a dict(dictionary).

we can access the values in dict by using indexes, but remember we do have user define indexes here that are keys. Because of this slicing is not possible in the dictionary.

let’s see how to access keys and values separately.

item() functions return keys and values in a list of tuples so we can access these values by using for loop also.

we can get value from the key in two ways.

  • d1.get( ‘key_name’ )
  • d1[ ‘key_name’ ]

both give us the same result but let me tell you the difference is.

let's create two dict first.

To avoid error we can use get( ) function.

student_1.get('fees',0) + student_2.get('fees',0)

now it will work correctly. It checks the value which we want is there in the dictionary or not if not then it will replace it with 0 or anything which we have provided.

Always use the get() function because it will not terminate our application.

________________________________________________________

What if we use the same key two times in that same dictionary?

It simply replaces an old value for that key with the new one.

________________________________________________________

We have seen a set data structure in the last articles.

A = { }

tell me whether it is a set or a dict?

It’s a dictionary then how to create an empty set?

this is how you can create an empty set.

In the next article, we will see more functions in the dictionary.

Thanks for reading!!

--

--