Access Items
Accessing Items in Python Dictionaries
1. Accessing Values with Keys:
# Use square brackets [] and the key to access the corresponding value
person = {'name': 'John', 'age': 30, 'city': 'New York'}
name = person['name'] # 'John'
age = person['age'] # 30
2. Using the get()
Method:
# The get() method allows you to retrieve the value associated with a key. If the key is not present, it returns a default value (or None if no default is provided)
person = {'name': 'John', 'age': 30, 'city': 'New York'}
name = person.get('name') # 'John'
occupation = person.get('job') # Returns None
3. Accessing Keys, Values, and Items:
# You can use the keys(), values(), and items() methods to get lists of keys, values, and key-value pairs (as tuples), respectively
person = {'name': 'John', 'age': 30, 'city': 'New York'}
keys_list = person.keys() # ['name', 'age', 'city']
values_list = person.values() # ['John', 30, 'New York']
items_list = person.items() # [('name', 'John'), ('age', 30), ('city', 'New York')]
4. Handling Missing Keys:
# You can use a combination of in and not in to check if a key is present in the dictionary before accessing its value
person = {'name': 'John', 'age': 30, 'city': 'New York'}
if 'name' in person:
name = person['name'] # Access the value if the key is present
else:
name = 'Unknown'
# Alternatively, you can use the get() method with a default value
person = {'name': 'John', 'age': 30, 'city': 'New York'}
name = person.get('name', 'Unknown')
These methods provide flexibility in accessing values from dictionaries, and you can choose the one that best suits your needs. Keep in mind that attempting to access a key that doesn't exist in the dictionary using square brackets will raise a KeyError. Using get() with a default value or checking for key existence helps handle such cases more gracefully.