Dictionaries are an essential data structure in Python that allow you to store and retrieve data using key-value pairs. They provide a powerful way to organize and manipulate data efficiently. In this article, we will explore how to create dictionaries and perform various operations on them. We will also cover different methods to iterate through dictionaries using loops. By the end, you will have a solid understanding of creating dictionaries and effectively looping through them.
Creating Dictionaries:
Example 1: Creating a dictionary using curly braces and key-value pairs
student = {"name": "John", "age": 20, "major": "Computer Science"} |
Example 2: Creating a dictionary using the dict() constructor and keyword arguments
student = dict(name="John", age=20, major="Computer Science") |
Example 3: Creating a dictionary using the zip() function
keys = ["name", "age", "major"]
student = dict(zip(keys, values)) |
Looping Through Dictionaries:
Example 1: Looping through keys using a for loop
| student = {"name": "John", "age": 20, "major": "Computer Science"}
for key in student: print(key) # Output: name, age, major |
Example 2: Looping through values using the values() method
student = {"name": "John", "age": 20, "major": "Computer Science"}
print(value) # Output: John, 20, Computer Science |
Example 3: Looping through key-value pairs using the items() method
|
|
Modifying and Adding Elements:
student = {"name": "John", "age": 20, "major": "Computer Science"}
print(student["age"])
|
Removing Elements:
del keyword
student = {"name": "John", "age": 20, "major": "Computer Science"}
print(student)
|
Conclusion: Dictionaries are a powerful data structure in Python that allow you to store and access data using key-value pairs. In this article, we explored different methods to create dictionaries and how to loop through them using for loops. We also covered modifying and removing elements from dictionaries. By mastering dictionaries and their operations, you will have a solid foundation for working with complex data structures and efficiently managing data in your Python programs.