Access Dictionary Items
Accessing Values by Key
Dictionary values can be retrieved by providing their key inside square brackets. If the key does not exist, this raises a KeyError. To avoid errors, you can use the get() method, which returns None (or a default value if specified) when the key is missing.
Example
# Accessing dictionary values
person = {"name": "John", "age": 30, "city": "New York"}
# Using square brackets (raises error if key not found)
print(person["name"])
# Using get() method (safer)
print(person.get("age"))
print(person.get("country")) # Returns None
print(person.get("country", "USA")) # Returns default value
Output
John 30 None USA
Checking Key Existence
Before accessing a value, you can check if a key exists in the dictionary using the 'in' keyword. This prevents KeyError exceptions when using square bracket access.
Example
# Checking if key exists
person = {"name": "John", "age": 30, "city": "New York"}
print("name" in person)
print("country" in person)
print("country" not in person)
Output
True False True
Accessing All Keys, Values, or Items
Dictionaries provide methods to access collections of their keys, values, or key-value pairs. The keys() method returns all keys, values() returns all values, and items() returns tuples of key-value pairs.
Example
# Accessing keys, values, and items
person = {"name": "John", "age": 30, "city": "New York"}
print("Keys:", list(person.keys()))
print("Values:", list(person.values()))
print("Items:", list(person.items()))
Output
Keys: ['name', 'age', 'city'] Values: ['John', 30, 'New York'] Items: [('name', 'John'), ('age', 30), ('city', 'New York')]