Python Dictionary – What is a Dictionary in Python?


What is a Dictionary in Python and How to Use It

In this tutorial, you'll learn what a dictionary is in Python, how to create, add and remove items to and from, and iterate a dictionary. Also, this tutorial teaches you how to count the number of elements in a dictionary.

What is a Dictionary in Python?

A dictionary is an unordered collection of items. While other collection data types, such as lists, sets, or tuples, have only values, the dictionary has both keys and values pair.

Creating a Dictionary in Python

Dictionary literals are written within curly brackets { }.

Here are examples:

students = {
"101": "Student A",
"102": "Student B",
"103": "Student C"
}
students = {
1: "Student 1",
2: "Student 2",
3: "Student 3"
}
items = {
"sales_price": 1200.50,
"cost": 1100,
"item_name": "Item 001",
"quantity": 20
}

Accessing Items

To access the items of a dictionary, you use the key inside square brackets [] to get its value.

dictionary[key]

or

dictionary.get(key)

Let's take a look at an example:

students = {
"101": "Student A",
"102": "Student B"
}
student = students["101"]
print (student)

Here, we get a value of the item that has key "101":

Output:

Student A

You also can use the dictionary get() method to get the same result as illustrated in the following example:

students = {
"101": "Student A",
"102": "Student B"
}
student = students.get("102")
print (student)

Output:

Student B

Adding Items

You can add an item to a dictionary by using a new key and assign a value to it.

dictionary[new_key] = value

Let's take a look at an example:

employees = {
1: "Employee A",
2: "Employee B",
}
employees[3] = "Employee C"
print (employees)

Here, we've created a dictionary containing two elements and then added a new item, which key is 3, and value is Employee C.

Output:

{1: 'Employee A', 2: 'Employee B', 3: 'Employee C'}

Removing Items

You can remove the item from a dictionary using the pop() method or the del keyword.

To remove the item at the specified key from a dictionary using the pop() method, use the following code:

Here is an example of using pop():

employees = {
1: "Employee A",
2: "Employee B",
}
employees[3] = "Employee C"
print (employees)
employees.pop(1)
print (employees)

Here, we've added a new item and then removed the exiting item, which key is 1.

Output:

{1: 'Employee A', 2: 'Employee B', 3: 'Employee C'}
{2: 'Employee B', 3: 'Employee C'}

Let's take a look at another example:

employees = {
1: "Employee A",
2: "Employee B"
}
del employees[1]
print (employees)

Here, we've used del instead of the pop() method.

Output:

{2: 'Employee B'}

You can also use the del keyword to delete the dictionary completely.

Here is an example:

items= {
"unit_price": 1500,
"unit_cost": 2300,
"name": "Item 001"
}
del items

Now the items dictionary has been deleted, so it's no longer available.

Changing Values

You can change the value of a specific item by assigning a new value to the existing key as follows:

dictionary_name[key] = value

Example:

students["name"] = "James"
students["id"] = "ID_00001"

If the key does not exist, it will be a new key and value pair.

Let's take a look at an example:

students = {
"name": "James"
}
print ("=== before ===")
print (students)
students["name"] = "John"
students["id"] = "ID_0001"
print ("=== after ===")
print (students)

Output:

=== before ===
{'name': 'James'}
=== after ===
{'name': 'John', 'id': 'ID_0001'}

Since the name key exists in the dictionary, the value has changed from James to John. But in case of the id key, since it doesn't exist, it is a new item of the dictionary.

Check if Key Exists

To check if a specified key is present in a dictionary, you use the in keyword and the IF statement.

Here is an example:

employee = {"ID": "20002", "DateOfBirth": "2010-10-01"}
print ("Check if Name exist!")
if "Name" in employee:
print ("The key \"Name\" already exists in the dictionary!")
else:
print ("The key \"Name\" doesn't exist in the dictionary!")
print("====")
print ("Check if ID exists!")
if "ID" in employee:
print ("The key \"ID\" exists in the dictionary!")
else:
print ("The key \"ID\" doesn't exist in the dictionary!")

Output:

Check if Name exist!
The key "Name" doesn't exist in the dictionary!

====
Check if ID exists!
The key "ID" exists in the dictionary!

Read more on how to use the IF statement in Python

In this tutorial, you've learned what a dictionary is in Python, how to create, add items to, remove items from, and iterate over a dictionary. Also, you've learned how to count the number of elements in a dictionary.

Leave a Reply

Your email address will not be published. Required fields are marked *