Python Basics

Python Dictionary

There are situations where we may want to store key and value pair data in a variable.

Dictionary

Dictionary in python: Variable which holds data in key and value pair form is known as dictionary.

Example:

registration_numbers={“Rahul”:”99ik89lm”, “Ajay”:”99ik90lm”, “Vijay”:”99ik91lm”, “Sachin”:”99ik92lm”, “Krishna”:”99ik933lm”}

How to print data from a dictionary variable in python?

To print a value from a dictionary variable we have to call the key.

Example:

registration_numbers={“Rahul”:”99ik89lm”, “Ajay”:”99ik90lm”, “Vijay”:”99ik91lm”, “Sachin”:”99ik92lm”, “Krishna”:”99ik933lm”}

print(registration_numbers[“Rahul”])

Output: 99ik89lm

Update Data in Python dictionary

To update data or value of key value pair in a dictionary, we need to assign a new value to the key.

Example:

registration_numbers={“Rahul”:”99ik89lm”, “Ajay”:”99ik90lm”, “Vijay”:”99ik91lm”, “Sachin”:”99ik92lm”, “Krishna”:”99ik933lm”}

registration_numbers[“Krishna”]=”000000″

print(registration_numbers[“Krishna”])

Output: 000000

How to delete dictionary elements?

If you want to delete any single element then just call del function of python and pass the key as below.

registration_numbers={“Rahul”:”99ik89lm”, “Ajay”:”99ik90lm”, “Vijay”:”99ik91lm”, “Sachin”:”99ik92lm”, “Krishna”:”99ik933lm”}

del registration_numbers[“Vijay”]

The above code will remove Vijay and its respective value from the dictionary regsitration_numbers

And for any reason, if you want to remove all the elements from a dictionary then call clear function as below.

registration_numbers={“Rahul”:”99ik89lm”, “Ajay”:”99ik90lm”, “Vijay”:”99ik91lm”, “Sachin”:”99ik92lm”, “Krishna”:”99ik933lm”}

registration_numbers.clear()

The above code will remove all the key and value pairs from registration_numbers

Note: Clear function only removes all the key value pair from the dictionary but not deletes the dictionary itself. It means after calling the clear function, all the key value pairs from the dictionary is removed but still the dictionary which is empty now, exists.

To delete the dictionary itself. Then call the del function of python.

registration_numbers={“Rahul”:”99ik89lm”, “Ajay”:”99ik90lm”, “Vijay”:”99ik91lm”, “Sachin”:”99ik92lm”, “Krishna”:”99ik933lm”}

del registration_numers

The above code completely deletes the dictionary.