Welcome to the topic of Dictionary Methods and Operations! This lesson is essential as it will help you navigate through various operations on dictionaries in Python. By the end of this lesson, you'll be able to manipulate dictionaries efficiently using methods like keys()
, values()
, items()
, get()
, update()
, and more!
A dictionary is a collection of key-value pairs. Keys are unique and must be immutable, while values can be any data type. Here's an example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
You can access the value of a key using its name:
print(my_dict['name']) # Outputs: John
keys()
: Returns all keys as a list.print(my_dict.keys()) # Outputs: dict_keys(['name', 'age', 'city'])
values()
: Returns all values as a list.print(my_dict.values()) # Outputs: ['John', 30, 'New York']
items()
: Returns all key-value pairs as a list of tuples.print(list(my_dict.items())) # Outputs: [('name', 'John'), ('age', 30), ('city', 'New York')]
get()
: Retrieves the value for the given key. If the key is not found, it returns a default value (optional).print(my_dict.get('name')) # Outputs: John
print(my_dict.get('address', 'Not Provided')) # Outputs: Not Provided (if 'address' does not exist in the dictionary)
update()
: Updates the dictionary with key-value pairs from another dictionary.another_dict = {'phone': '123-456-7890'}
my_dict.update(another_dict)
print(my_dict) # Outputs: {'name': 'John', 'age': 30, 'city': 'New York', 'phone': '123-456-7890'}
Let's create a simple address book using dictionaries and their methods.
address_book = {
'Alice': {'address': '123 Main St', 'phone': '555-1234'},
'Bob': {'address': '456 Oak St', 'phone': '555-5678'},
'Charlie': {'address': '789 Pine St', 'phone': '555-9012'}
}
# Search for Bob's phone number
print(address_book['Bob']['phone']) # Outputs: 555-5678
# Update Charlie's phone number
address_book['Charlie']['phone'] = '555-3456'
print(address_book) # Outputs: {...} (with updated Charlie's phone number)
What causes it: Attempting to access a key that does not exist in the dictionary.
print(my_dict['non_existent_key']) # Outputs: KeyError: 'non_existent_key'
Solution: Use the get()
method with a default value or check if the key exists using the in
keyword.
# Using get()
print(my_dict.get('non_existent_key', 'Key not found')) # Outputs: Key not found
# Checking if key exists
if 'non_existent_key' in my_dict:
print(my_dict['non_existent_key']) # This will never execute because the key does not exist
else:
print('Key not found')
Why it happens: You are trying to access a key that is not present in the dictionary.
How to prevent it: Always check if the key exists before attempting to access its value.
get()
method with a default value instead of checking if the key exists, as it can lead to cleaner code.keys()
, values()
, and items()
return new lists each time they are called, so store their results if you need to use them multiple times.keys()
, values()
, and items()
for manipulating key-value pairs.get()
method can retrieve values with a default value if the key is not found, and the update()
method updates the dictionary with new key-value pairs.in
keyword or the get()
method to handle this case gracefully.