Introduction
In Python, a dictionary is an unordered collection of data values that are used to store data in key-value pairs. Unlike other data types like lists or tuples, dictionaries allow you to quickly retrieve data using keys, which is very useful in various programming scenarios. In this guide, we will explore how to use Python dictionaries, how to create them, and the different operations that can be performed on them.
Objective
The main objective of this topic is to understand the basic structure and operations of Python dictionaries. We will learn how to create, access, and modify dictionaries, as well as iterate through key-value pairs. By the end of this tutorial, you will be able to utilize Python dictionaries effectively in your own projects.
Python Code Example: Working with Dictionaries
# Example Python program demonstrating basic dictionary operations
# Creating a dictionary
student_grades = {
"Alice": 85,
"Bob": 92,
"Charlie": 78,
"David": 88
}
# Accessing values using keys
print("Alice's grade:", student_grades["Alice"])
# Adding a new key-value pair
student_grades["Eve"] = 90
# Modifying an existing key-value pair
student_grades["Bob"] = 95
# Removing a key-value pair
del student_grades["Charlie"]
# Iterating through dictionary
print("\nUpdated student grades:")
for student, grade in student_grades.items():
print(f"{student}: {grade}")
Program Explanation
The above Python program demonstrates various operations that can be performed on dictionaries:
- Creating a dictionary: We create a dictionary called
student_grades
that holds the names of students as keys and their corresponding grades as values. - Accessing values: We access Alice’s grade using the key “Alice” and print the result.
- Adding new key-value pairs: A new student, Eve, is added to the dictionary with a grade of 90.
- Modifying existing key-value pairs: Bob’s grade is updated from 92 to 95.
- Removing key-value pairs: We remove Charlie from the dictionary using the
del
statement. - Iterating through the dictionary: We use a
for
loop to print all student names and their grades.
How to Run the Program
To run the above Python program, follow these steps:
- Open your text editor or IDE (e.g., Visual Studio Code, PyCharm, or any Python-friendly editor).
- Create a new file and name it
dictionary_example.py
. - Copy and paste the code into the file.
- Save the file and open a terminal or command prompt in the directory where the file is saved.
- Type
python dictionary_example.py
and press Enter to execute the program.