Python Dictionary and its operations

Hello everyone, Welcome back to proramminginpython.com. Here in this post am going to introduce you to one of the popular python data type – Dictionary. Lists and Tuples are some of the other data types. Dictionaries are indexed by keys and can be of any immutable type. These are unordered key-value pairs with unique keys.

Dictionary can be created simply by writing curly braces {} an example dictionary will look like {'key1': 'value1', 'key2': 'value2'}

Now let’s go through the operations that can be performed on dictionaries.

You can watch the video in youtube here

 

Program on Github

Python Dictionary Operations – Code Visualization

Create Dictionary

I will create a dictionary named my_infoand add some key-value pairs to it.

and print it.

Python Dictionary Operations - programminginpython.com
Python Dictionary Operations – programminginpython.com

Program on Github

Accessing Values

Now I can access the elements in the dictionary by its key, here I will print the value of the key 'Name'.

Python Dictionary Operations - programminginpython.com
Python Dictionary Operations – programminginpython.com

Modifying values

I can also modify the existing elements in the dictionary, here I will modify the value of key 'Age'

Python Dictionary Operations - programminginpython.com
Python Dictionary Operations – programminginpython.com

Program on Github

Length of dictionary

I can also find the length of the dictionary, using the built-in method len() which gives the total number of items in the dictionary.

Python Dictionary Operations - programminginpython.com
Python Dictionary Operations – programminginpython.com

Delete elements

I can also delete a particular key from a dictionary, here I will delete key 'Website'

Similarly, I can remove all the elements using a function called clear() which empties all the elements in the dictionary

I can also delete the entire dictionary,

These are some of the operations that can be performed on dictionaries.

Program on Github

The complete code for above snippets,

 

Leave a Reply