Introduction to Python Dictionaries

If you are new to Python, you might have heard of a data structure called a dictionary. But what is a dictionary and how can you use it in your code? In this blog post, we will answer these questions and more. We will start with the basics and then explore some advanced features of dictionaries.

What is a dictionary & How to Create Them?

A dictionary is a collection of key-value pairs, where each key is associated with a value.

You can create a dictionary by using curly braces {} and separating the key-value pairs by commas.

For example, here is a dictionary that stores some information about a person:

person = {
    "name": "Alice",
    "age": 25,
    "hobbies": ["reading", "cooking", "traveling"]
}

In this dictionary, the keys are "name", "age", and "hobbies", and the values are "Alice", 25, and ["reading", "cooking", "traveling"].

The keys must be immutable, which means they cannot be changed after they are created. The values can be any type of data, such as numbers, strings, lists, or even other dictionaries.

We are going to use this dictionary for most of the examples in the following sections.

Why are dictionaries useful in Python?

Dictionaries are very useful because they allow you to store and access data efficiently and flexibly.

You can use dictionaries to represent complex data structures, such as user profiles, product catalogs, or configuration settings.

You can also use dictionaries to store data that is dynamic and unpredictable, such as user input, web scraping results, or API responses.

Dictionaries are also easy to work with, as they have many methods and operators that make them convenient and powerful.

How to access values in a dictionary?

Think of a dictionary key as a real key that opens a door to a value. You can use the key to get the value or change it. Keys are unique, so you can’t have two keys that open the same door.

To access the value associated with a key, you can use square brackets [] and specify the key inside them. For example, to get the name of the person, you can write:

name = person["name"] # Alice

If the key does not exist in the dictionary, you will get a KeyError.

To avoid this, you can use the get() method, which returns a default value if the key is not found. For example, to get the occupation of the person, you can write:

occupation = person.get("occupation", "unknown")

This will return "unknown" if the key "occupation" is not in the dictionary.

How to add or update values in a dictionary?

To add or update a value in a dictionary, you can use the assignment operator = and specify the key and the value. For example, to add the occupation of the person, you can write:

person["occupation"] = "teacher"

This will create a new key-value pair if the key does not exist, or update the existing value if the key exists.

How to delete values from a dictionary?

To delete a value from a dictionary, you can use the del statement and specify the key.

For example, to delete the age of the person, you can write:

del person["age"]

This will remove the key-value pair from the dictionary. If the key does not exist, you will get a KeyError.

You can also use the pop() method, which returns and removes the value associated with a key. For example, to get and delete the hobbies of the person, you can write:

hobbies = person.pop("hobbies")

This will return ["reading", "cooking", "traveling"] and remove the key-value pair from the dictionary. If the key does not exist, you can specify a default value to return. For example:

favorite_color = person.pop("favorite_color", "blue")

This will return “blue” if the key “favorite_color” is not in the dictionary.

How to iterate over a dictionary?

To iterate over a dictionary, you can use a for loop and access either the keys or the values or both. For example, to print all the keys in the person dictionary, you can write:

for key in person:
    print(key)

This will print:

name
occupation

To print all the values in the person dictionary, you can write:

for value in person.values():
    print(value)

This will print:

Alice
teacher

To print both the keys and the values in the person dictionary, you can write:

for key, value in person.items():
    print(key, value)

This will print:

name Alice
occupation teacher

Nested dictionaries:

You can have dictionaries inside dictionaries, which allow you to store more complex data structures. For example, you can create a dictionary that stores information about multiple people using nested dictionaries:

people = {
    "Alice": {
        "age": 25,
        "occupation": "teacher",
        "hobbies": ["reading", "cooking", "traveling"]
    },
    "Bob": {
        "age": 30,
        "occupation": "engineer",
        "hobbies": ["gaming", "coding", "biking"]
    },
    "Charlie": {
        "age": 35,
        "occupation": "doctor",
        "hobbies": ["running", "swimming", "golfing"]
    }
}

To access the values in a nested dictionary, you can use multiple square brackets. For example, to get the occupation of Bob, you can write:

occupation = people["Bob"]["occupation"]

Conclusion

In this blog post, we have learned what a dictionary is and how to use it in Python. We have also explored some advanced features of dictionaries, such as nested dictionaries.

Dictionaries are very useful and versatile data structures that can help you store and manipulate data in your code.

I hope this blog post has helped you understand the basics of dictionaries in Python. If you have any questions or feedback, feel free to leave a comment below. Happy coding!

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *