Working with Dictionaries in Python
In Python, dictionaries are used to store data in key-value pairs, where each key is unique. This structure is useful for managing and accessing data where each piece of information can be uniquely identified by a key.
Creating Dictionaries
To create a dictionary in Python, you define a collection of key-value pairs using curly braces {}
. Keys can be strings, numbers, or tuples, and values can be of any type.
# Creating a dictionary
student = {
"name": "Alice",
"age": 20,
"grades": [85, 90, 92]
}
print(student)
Accessing Values
You can access the values in a dictionary by referring to their keys. This allows you to retrieve and manipulate the data stored in the dictionary.
# Accessing values from the dictionary
print("Student Name:", student["name"])
print("Student Age:", student["age"])
print("Student Grades:", student["grades"])
Adding and Updating Entries
You can add new key-value pairs to an existing dictionary or update the values of existing keys. This flexibility allows you to manage and modify your data easily.
# Adding a new entry
student["email"] = "alice@example.com"
# Updating an existing entry
student["age"] = 21
print(student)
Deleting Entries
To remove an entry from a dictionary, you use the del
statement or the pop()
method. This removes the key-value pair from the dictionary.
# Deleting an entry
del student["email"]
print(student)
Iterating Through a Dictionary
You can loop through a dictionary to access all key-value pairs. This is useful for performing operations on each entry in the dictionary.
# Iterating through the dictionary
for key, value in student.items():
print(f"{key}: {value}")
Nested Dictionaries
Dictionaries can contain other dictionaries as values. This allows you to create more complex data structures, such as hierarchical data.
# Creating a nested dictionary
school = {
"students": {
"Alice": {"age": 20, "grades": [85, 90, 92]},
"Bob": {"age": 22, "grades": [78, 84, 89]}
},
"teachers": {
"Mr. Smith": {"subject": "Math", "years": 10},
"Ms. Johnson": {"subject": "English", "years": 8}
}
}
print(school)
Import Links
Here are some useful import links for further reading: