Creating Dictionaries
Dictionaries store data in key‑value pairs. Keys act like labels, and values hold the associated data. This structure makes dictionaries ideal for representing structured information, like student profiles.
student = {"name": "Maya", "age": 21, "major": "Physics"}
print(student)
Accessing Values
You can retrieve values using their keys. Direct access with [] is fast, while get() is safer because it avoids errors if the key doesn’t exist.
print(student["name"])
print(student.get("major"))
Adding New Keys
Dictionaries are mutable, so you can add new key‑value pairs at any time. This makes them flexible for evolving datasets, like adding a student’s university to their profile.
student["university"] = "City University"
print(student)
Looping Through Dictionaries
Using .items(), you can iterate over both keys and values. This is useful for displaying or processing all the information stored in a dictionary.
for key, value in student.items():
print(key, "=", value)
My take
Dictionaries are perfect for structured data. They allow fast lookups, flexible updates, and easy iteration, making them essential for mapping relationships between keys and values.
Top comments (0)