Python - Dictionary Methods Part 1: Accessing and Retrieving Data
These methods focus on fetching values and keys or exploring dictionary contents.
Methods and Examples
get() Method Retrieves the value associated with a key. If the key doesn’t exist, it returns a default value (default is None).
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict.get("name")) # Output: Alice
print(my_dict.get("country", "USA")) # Output: USA
Explanation: Use get() to safely access dictionary values without raising a KeyError.
keys() Method Returns a view object containing all dictionary keys.
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
Explanation: The keys() method is useful for iterating over all keys.
values() Method Returns a view object containing all dictionary values.
print(my_dict.values()) # Output: dict_values(['Alice', 25, 'New York'])
Explanation: The values() method provides access to all dictionary values in one go.
items() Method Returns a view object containing key-value pairs as tuples.
print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
Explanation: The items() method is particularly helpful in for-loops for unpacking keys and values.