Learn about Python Dictionary

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, 'name', 'age', 'spouse' are the dict keys, and corresponding are the values.

Dictionary Methods

There are several methods that you can use to perform various task with python dictionaries, they are, 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 declaring a Python dictionary directly, 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

We learned how to declare a python dictionary. Now we need to add more data to it at the run time. Let's do it.


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 them one by one.

Method1: 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

Method2: 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

Method3: 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 list as a value of a key in the python dictionary. Let's see an example.


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. The below example is for you.


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: pop() method


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


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. del() and clear() method. The first one will delete the entire dictionary and the second one 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


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, we learned about the Python Dictionary and all its functionalities. We covered several methods to perform various operations with the python dictionary. In summarize, we learned the following topics:

1. How to create a dictionary,

2. Access data items from there,

3. Add 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