DEV Community

Cover image for Dictionaries Demystified: Key Value Magic in Python
Mary Nyandia
Mary Nyandia

Posted on

Dictionaries Demystified: Key Value Magic in Python

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)

Enter fullscreen mode Exit fullscreen mode

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"))

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)