Dictionary Inspection & Control Methods
Python dictionaries provide built-in methods to safely search for data, extract keys and values, and update multiple items easily.
Let's use a simple student profile to understand each method:
student = {"name": "Rahul", "age": 20, "city": "Hyderabad"}
1. Safe Lookups with .get()
When you use square brackets student["phone"] to search for a missing key, Python crashes with a KeyError.
Using .get("key") is much safer because it returns None (or a default fallback message you choose) instead of crashing your program:
student = {"name": "Rahul", "age": 20, "city": "Hyderabad"}
# 1. Look up an existing key
print(student.get("name"))
# Output: Rahul
# 2. Look up a missing key (returns None, no crash!)
print(student.get("phone"))
# Output: None
# 3. Provide a custom fallback message if key is missing
print(student.get("phone", "Phone number not provided"))
# Output: Phone number not provided
2. Extracting Keys (.keys()), Values (.values()), and Pairs (.items())
Python allows you to inspect all parts of a dictionary separately:
2.1 The .keys() Method (Get All Field Names)
Returns a list-like view of all keys in the dictionary:
student = {"name": "Rahul", "age": 20, "city": "Hyderabad"}
print(student.keys())
# Output: dict_keys(['name', 'age', 'city'])
2.2 The .values() Method (Get All Stored Data)
Returns a list-like view of all values:
student = {"name": "Rahul", "age": 20, "city": "Hyderabad"}
print(student.values())
# Output: dict_values(['Rahul', 20, 'Hyderabad'])
2.3 The .items() Method (Get Key-Value Pairs)
Returns each key and value grouped together inside a tuple (key, value):
student = {"name": "Rahul", "age": 20, "city": "Hyderabad"}
print(student.items())
# Output: dict_items([('name', 'Rahul'), ('age', 20), ('city', 'Hyderabad')])
3. Updating Multiple Keys at Once (.update())
The .update() method merges new key-value pairs into a dictionary or updates existing values in one step:
student = {"name": "Rahul", "age": 20, "city": "Hyderabad"}
# Update age and add a new phone number
student.update({"age": 21, "phone": "9876543210"})
print(student)
# Output: {'name': 'Rahul', 'age': 21, 'city': 'Hyderabad', 'phone': '9876543210'}
4. Removing Keys (.pop())
The .pop("key") method removes a specific key and returns its value:
student = {"name": "Rahul", "age": 20, "city": "Hyderabad"}
# Remove "city" and get its value
removed_city = student.pop("city")
print("Removed:", removed_city) # Output: Removed: Hyderabad
print(student) # Output: {'name': 'Rahul', 'age': 20}
- Dict Views are not Lists:
.keys(),.values(), and.items()return dynamic view objects. Wrap inlist(user.keys())if positional indexing ([0]) is required.
Quick Summary
- Safe Lookup (
.get(key, default)): AvoidsKeyErrorby returningNoneor a custom fallback if the key is not found. - Extraction Methods:
.keys()(all keys),.values()(all values), and.items()(all key-value tuples). - Updating (
.update()): Merges another dictionary or key-value sequence directly into the existing dictionary. - Deletion:
.pop(key)removes a key and returns its value;.clear()empties the entire dictionary.
What's Next?
Let's explore how to loop through dictionaries and organize complex nested structures in the next lesson!