Dictionary in Python

Introduction

Python dictionary(in short 'dict') is a collection of arbitrary data. Items are stored in the form of keys and their corresponding values. Keys and values are separated by a colon ':' and each item is separated by a comma ','.

Another important thing about Python dicts is that they are mutable (in short, you can change the contents or state of an object at runtime).

Example

iron_man = {

'name': "Robert Downey",

'age': 55,

'spouse': "Susan Downey"

}

Here, 'iron_man' is a dictionary variable, and 'name', 'age', and 'spouse' are the dict keys and the corresponding values.

Dictionary Methods

There are several built-in methods that you can use to perform various tasks with Python Dictionaries.

Examples

dict(), keys(), values(), items(), pop(), del(), clear(), etc.

Create a python dictionary

Creating a python dictionary is pretty straightforward. See the example below.


python_dict = {
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
}
print(python_dict)

Output

{'website': 'PySeek', 'language': 'Python', 'topic': 'Python Dictionary'}

Create a dictionary using the dict() method

Instead of following the previous technique, you can use the dict() method to do the same.


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})
print(python_dict)

Output

{'website': 'PySeek', 'language': 'Python', 'topic': 'Python Dictionary'}

Add data to a dictionary

You learned how to declare a python dictionary. Now you will learn how to add data items to a python dictionary.

In the example below, we want to add one more key and corresponding value to the dictionary. Let's see how we can do this.


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})
# Add data to a python dictionary
python_dict['category'] = "Basic"
print(python_dict)

Output

{'website': 'PySeek', 'language': 'Python', 'topic': 'Python Dictionary', 'category': 'Basic'}

Access data from a dictionary

You can access data items from a Python Dictionary using multiple ways. Let's see one by one.

Method 1: Using For Loop


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})

print("----All the keys----")
for key in python_dict:
print(key)

print("\n----Values-----")
for value in python_dict:
print(python_dict[value])

Output

----All the keys----
website
language
topic

----Values-----
PySeek
Python
Python Dictionary

Method 2: Using keys() and values() methods

Here, we will use the keys() and values() methods to get the keys and corresponding values respectively from the Python dictionary.


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})

print("----All the keys----")
for key in python_dict.keys():
print(key)

print("\n----Values-----")
for value in python_dict.values():
print(value)

Output

----All the keys----
website
language
topic

----Values-----
PySeek
Python
Python Dictionary

Method 3: Using the items() method

items() method returns an object that contains key-value pair.


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})

for key, item in python_dict.items():
print(f"The key is: {key} and the corresponding value is: {item}")

Output

The key is: website and the corresponding value is: PySeek
The key is: language and the corresponding value is: Python
The key is: topic and the corresponding value is: Python Dictionary

Add a Python List to a dictionary

You can add a Python List as a value of a key in the Python Dictionary. See the example below.


iron_man = dict({"name" : "Robert Downey", "age" : 55, "spouse" :
"Susan Downey"})
iron_man['upcoming_movies'] = ['Black Widow', 'Sherlock Holmes 3']
print(iron_man)

Output

{'name': 'Robert Downey', 'age': 55, 'spouse': 'Susan Downey', 'upcoming_movies': ['Black Widow', 'Sherlock Holmes 3']}

Update data elements in a dictionary

You can update the existing values of any key in a dictionary.


iron_man = dict({"name" : "Robert Downey", "age" : 55, "spouse" :
"Susan Downey"})
iron_man["age"] = 56
print(iron_man)

Output

{'name': 'Robert Downey', 'age': 56, 'spouse': 'Susan Downey'}

Delete data items from a dictionary

Python dictionary allows deleting any keys with their corresponding values. There are two methods to perform this task.

Method 1: Using pop() method

Here, you need to mention the key name directly in the pop() function. As a result, the corresponding values will be deleted from that dictionary along with the key.


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})

# Deleting a key with the corresponding value
python_dict.pop('topic')
print(python_dict)

Output

{'website': 'PySeek', 'language': 'Python'}

Method 2: del() method

Instead of following the previous method, you can use the 'del' method to delete an item from a dictionary. See the example below.


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})

# Deleting a key with the corresponding value
del python_dict['topic']
print(python_dict)

Output

{'website': 'PySeek', 'language': 'Python'}

Delete the Dictionary

There are two methods to perform the deleting operation on the entire Python Dictionary. del() and clear() method. 

The first one (del() method) will delete the entire dictionary and the second one (clear() method) will delete all the keys and values stored there but not the entire dictionary.

Method 1: del() method


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})

# Deleting the entire dictionary
del python_dict
print(python_dict)

Output

Traceback (most recent call last):
  File "/home/suvankar/Desktop/sample_code.py", line 10, in <module>
    print(python_dict)
NameError: name 'python_dict' is not defined

Method 2: clear() method

In this case, all the presence data inside the dictionary will be deleted but not the dictionary.


python_dict = dict({
'website': "PySeek",
'language': "Python",
'topic': "Python Dictionary"
})

# Clearing all the data
python_dict.clear()
print(python_dict)

Output

{}

Summary

In this tutorial, you learned about the Python Dictionary and all its functionalities. We covered several methods to perform various operations with the Python Dictionary. In summary, we covered the following topics:

1. How to create a dictionary.

2. Access data items from there.

3. Add new data to a dictionary.

4. Delete or remove and clear a dictionary, etc.

If you have any queries related to this topic, please let me know in the comment section; You will get an immediate response.

Thanks for reading!💙

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post