Dictionaries

Dictionaries are a bag of key value pairs which is written inside two curly braces. It is a collection of key values pairs that is not ordered, can be changeable and can be indexed.

Rather than indexes, in any other collections like lists, arrays, etc., items can be obtained via Key.

Now let’s see how to create a dictionary in Python and access the first element.

Example:

We have created a dictionary called as “personDict” that stores two values, name and the place.

In the first print statement, we are displaying the entire “personDict” dictionary.

In the second print statement, we are displaying the value of the name Key of the “personDict”.

Let’s see what is the output here.

Output:

The first print statement has printed the entire dictionary.

The second print statement has printed the value of the name Key of the dictionary.

Changing the value

We will try to change the value of the name key in the dictionary and let’s print the dictionary again.

Example:

The highlighted statement personDict[“name”] = “UpdatedName” changes the value of name key from “Hepsi” to “UpdatedName”.

Output:

The value of ‘name’ is changed to ‘UpdatedName’.

Loops and Dictionaries

Let’s see with examples how to loop through all the elements inside dictionary and display both Key and Values. This can be achieved easily with for loop.

First, let’s see how to display all the Keys in the dictionary.

Example:

In the above code, for loop is used where we are looping all the items. It will display the keys.

Output:

It displayed both the keys in the personDict dictionary i.e., name and place.

Let’s see how to display all the values in the dictionary.

Example:

In the above code, k contains all the keys and we are accessing the values using the keys in the print statement.

Let’s see what is the output.

Output:

It is displaying all the values associated with the keys.

There are variety of advanced operations that we can perform using Dictionaries. However, I would restrict myself in listing down all those here.

We will learn all the advanced concepts as we progress in our learning.

Do come back for my next post. 😊

Leave a comment

Design a site like this with WordPress.com
Get started