Python Tutorial
About Lesson

In this Python Dictionary lesson i want to show you Creating Dictionary in Python, a python dictionary is a collection of data values which is unordered, and it is changeable. or we can say a dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key. A key’s value can be a number, a string, a list, or even another dictionary. In fact, you can use any object that you can create in Python as a value in a dictionary. In Python dictionaries are written with curly brackets, and they have keys and values.

 

 

Let’s create our first dictionary. in this example we have keys for the dictionary and also values to every keys.

 

 

 

This is the result.

Python Dictionary - Creating Dictionary in Python
Python Dictionary – Creating Dictionary in Python

 

 

 

Now if you want to access the value of a dictionary, you can use the key of that dictionary.

 

 

 

Run the code and this is the result.

Python Dictionary
Python Dictionary

 

As with most new programming concepts, using dictionaries takes practice. Once you’ve worked with dictionaries for a bit you’ll soon see how effectively they can model real world situations.

 

 

 

Adding New Key Value Pair

Now let’s learn how to add new key value pairs in python dictionary. Dictionaries are dynamic structures, and you can add new key­ value pairs to a dictionary at any time. For example, to add a new key­ value pair, you would give the name of the dictionary followed by the new key in square brackets along with the new value.

 

 

 

Creating Empty Dictionary

Some times you need to create empty dictionary,  and then add some items to the dictionary, to start filling an empty dictionary,  define a dictionary with an empty set of braces and then add each key ­value pair on its own line.

 

 

 

Run the code and this is the result.

Empty Dictionary in Python
Empty Dictionary in Python

 

 

 

Updating the value of Dictionary

To modify a value in a dictionary, give the name of the dictionary with the key in square brackets and then the new value you want associated with that key.

 

 

 

This is the result.

Python Updating Dictionary
Python Updating Dictionary

 

 

Removing Key Value Pairs

When you no longer need the value that’s stored in a diction­ary, you can use the del keyword to remove a key­ value pair. 

 

 

 

Using get() to Access Values

Using keys in square brackets to retrieve the value from a dictionary might cause some problems, if the key doesn’t exist, you’ll get an error, so we can use get to handle this error.

 

Thank you for visiting my website! If you enjoyed the free courses, please consider supporting my works on Patreon.
Exercise Files
No Attachment Found
No Attachment Found