Dictionaries in Python are powerful data structures that store data in key-value pairs. They allow us to efficiently manage and retrieve data using unique keys. Whether you’re handling user information, storing configurations, or managing data collections, dictionaries are incredibly useful. In this article, we’ll walk through three practical examples of working with dictionaries in Python, providing clear explanations and code snippets for each.
Imagine you are building a simple contact book application to store and retrieve information about your friends. You can use a dictionary to store each friend’s name as the key and their contact number as the value.
# Creating a contact book dictionary
contact_book = {
'Alice': '123-456-7890',
'Bob': '987-654-3210',
'Charlie': '555-555-5555'
}
# Accessing a contact's number
friend_name = 'Alice'
contact_number = contact_book[friend_name]
print(f'{friend_name} can be reached at {contact_number}.')
In this example, we created a contact book with three entries. To access Alice’s contact number, we simply use her name as the key. This is a straightforward way to retrieve information from our dictionary.
KeyError
. To avoid this, you can use the get()
method, which returns None
if the key is not found.Continuing with our contact book, you may want to add a new friend or update an existing friend’s contact number. Using dictionaries, this is simple and efficient.
```python
contact_book[’David’] = ‘444-444-4444’ print(f’Added David: {contact_book[