Python Dictionaries
Dictionaries in Python
Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable, and does not allow duplicate keys. They are highly optimized for fast lookup operations, functioning as hash tables behind the scenes.
Accessing Items
You can access the items of a dictionary by referring to its key name inside square brackets or using the .get() method. The .get() method is safer because it returns None instead of throwing a KeyError if the key is missing.
Dictionaries can be modified by adding new keys, changing existing values, or removing entries using the pop() or del keywords. The keys(), values(), and items() methods let you loop through dictionary contents efficiently.
Python dictionaries support nesting, meaning a dictionary can contain other dictionaries. This is highly useful for storing structured data like JSON configurations or complex user profiles.
Since Python 3.7, dictionaries maintain the insertion order of keys, making them reliable for ordered key-value processing.
Safe Lookups with Get
Using the get() method prevents program crashes when keys do not exist. You can supply a default fallback value that is returned in case the key is missing.
user = {"id": 1, "active": True}
print("ID:", user.get("id"))
print("Missing Key Safely:", user.get("email", "No Email Found"))student = {
"name": "David",
"major": "Computer Science",
"grad_year": 2026
}
print("Student details:", student)
print("Major:", student.get("major"))
student["gpa"] = 3.9
print("Keys:", list(student.keys()))