Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is a dictionary in Python

Understanding Dictionaries in Python

When you're just starting out with programming, understanding the different ways to store and manage data can be one of the most crucial steps towards building useful applications. In Python, one of the most flexible and powerful data structures available to you is the dictionary.

What is a Dictionary?

Imagine you have a real-life dictionary. You use it to look up the definition of a word, right? In Python, a dictionary works in a similar way. It stores data in a key-value pair. This means that for each unique key, there is a corresponding value. Just like you would look up a word (the key) in a dictionary to find its definition (the value), you use keys in Python dictionaries to retrieve values.

Here's a simple analogy: think of a dictionary as a customizable filing cabinet. Each drawer (key) is labeled with a unique tag and contains files (values). You can quickly access any file by knowing which drawer to open.

Creating a Dictionary

Creating a dictionary in Python is straightforward. You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces {}. A colon : separates each key from its value.

# A simple dictionary that maps a fruit to its color
fruit_colors = {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'}
print(fruit_colors)

When you run this code, it will display the fruit_colors dictionary with the fruits as keys and their associated colors as values.

Accessing Data in a Dictionary

To access the value associated with a specific key, you use the square bracket notation [], much like you do with lists, but instead of using the index number, you use the key.

# Access the color of an apple
apple_color = fruit_colors['apple']
print(apple_color) # Output: red

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 or a default value you specify if the key is not found.

# Using .get() to safely access a key
cherry_color = fruit_colors.get('cherry')
print(cherry_color) # Output: red

dragonfruit_color = fruit_colors.get('dragonfruit', 'unknown')
print(dragonfruit_color) # Output: unknown

Modifying a Dictionary

Dictionaries are mutable, meaning you can change them after they are created. You can add new key-value pairs, update existing values, or delete pairs altogether.

Adding and Updating

To add a new key-value pair, you simply assign a value to a new key:

# Add a new fruit
fruit_colors['orange'] = 'orange'
print(fruit_colors)

If the key already exists, the assignment will update the value associated with that key:

# Update the color of a banana
fruit_colors['banana'] = 'green'
print(fruit_colors)

Deleting

You can remove key-value pairs using the del statement or the .pop() method.

# Using del to remove a key-value pair
del fruit_colors['cherry']
print(fruit_colors)

# Using .pop() to remove and return the value of the key
apple_color = fruit_colors.pop('apple')
print(apple_color)
print(fruit_colors)

Iterating Through a Dictionary

You can loop through a dictionary to access its keys, values, or both. Here's how you can iterate over each aspect of a dictionary:

Keys

# Loop through keys
for fruit in fruit_colors:
    print(fruit)

Values

# Loop through values
for color in fruit_colors.values():
    print(color)

Key-Value Pairs

# Loop through key-value pairs
for fruit, color in fruit_colors.items():
    print(f"{fruit} is {color}")

Dictionary Comprehensions

Just like list comprehensions, Python supports dictionary comprehensions. These allow you to create dictionaries from iterable data structures in a concise and readable way.

# Create a dictionary with numbers and their squares
squares = {number: number ** 2 for number in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

When to Use Dictionaries

Dictionaries are ideal when you need to associate unique keys with values and when you need to retrieve data quickly based on those keys. They are optimized for retrieving data (known as lookup operations), making them incredibly efficient for this purpose.

Conclusion

Dictionaries in Python are like the Swiss Army knife of data structures—versatile and useful in a wide array of situations. They allow you to store and manage data in a way that is intuitive and efficient, making your journey into programming that much smoother. Whether you're cataloging fruit colors or storing user information in a web application, dictionaries will likely become one of your go-to tools. So next time you need to pair some data together, remember the humble dictionary, your dependable data structure for quick and easy data retrieval. Keep experimenting with dictionaries, and you'll discover just how powerful a simple data structure can be in the hands of a creative programmer.