Working with Dictionaries in Python - 3 Practical Examples

Explore practical examples of working with dictionaries in Python, perfect for beginners and non-experts.
By Taylor

Introduction to Dictionaries in Python

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.

Example 1: Creating and Accessing a Dictionary

Context

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.

Notes

  • If you try to access a key that doesn’t exist in the dictionary, Python will raise a KeyError. To avoid this, you can use the get() method, which returns None if the key is not found.

Example 2: Adding and Updating Entries

Context

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

Adding a new contact

contact_book[’David’] = ‘444-444-4444’ print(f’Added David: {contact_book[