Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to create a dictionary in Python

Introduction

Python is a versatile and powerful programming language that is widely used by beginners and experts alike. It is known for its readability and simplicity, which makes it an ideal choice for someone who is learning programming for the first time. In this blog post, we will discuss a fundamental data structure in Python called the dictionary. We will cover the basics of creating and manipulating dictionaries, explore some common use cases, and provide examples to help you understand this important concept.

What is a Dictionary?

A dictionary in Python is a mutable, unordered collection of key-value pairs. In simple terms, it is like a real-life dictionary where each word (key) has a corresponding definition (value). Dictionaries are incredibly useful when you want to store and retrieve information based on a unique identifier, such as looking up the definition of a word or finding the price of a product based on its name.

In Python, dictionaries are also known as associative arrays, maps, or hash maps in other programming languages. They provide an efficient way to store and access data, allowing you to retrieve values based on a specific key rather than having to search through an entire list.

Creating a Dictionary

To create a dictionary in Python, you can use curly braces {} and separate the keys and values with a colon :. Here is an example of a dictionary containing the names and ages of three people:

ages = {"Alice": 30, "Bob": 25, "Charlie": 22}
print(ages)

Output:

{'Alice': 30, 'Bob': 25, 'Charlie': 22}

In this example, the names ("Alice", "Bob", and "Charlie") are the keys, and their respective ages (30, 25, and 22) are the values. Notice that the keys and values in the dictionary are enclosed in curly braces, and each key-value pair is separated by a comma.

You can also create an empty dictionary using the dict() constructor:

empty_dict = dict()
print(empty_dict)

Output:

{}

Accessing Values in a Dictionary

To access the value associated with a specific key in a dictionary, you can use square brackets [] and the key as the index. For example, let's retrieve the age of "Alice" from our ages dictionary:

alice_age = ages["Alice"]
print(alice_age)

Output:

30

Keep in mind that if you try to access a key that does not exist in the dictionary, Python will raise a KeyError. To avoid this, you can use the get() method, which returns a default value if the key is not found:

unknown_age = ages.get("Unknown", "Not found")
print(unknown_age)

Output:

Not found

In this example, since the key "Unknown" does not exist in the ages dictionary, the get() method returns the default value "Not found".

Modifying a Dictionary

Dictionaries in Python are mutable, which means that you can add, update, or remove key-value pairs after the dictionary has been created.

Adding Key-Value Pairs

To add a new key-value pair to a dictionary, simply assign a value to a new key using the assignment operator =:

ages["David"] = 35
print(ages)

Output:

{'Alice': 30, 'Bob': 25, 'Charlie': 22, 'David': 35}

In this example, we added a new key "David" with the value 35 to the ages dictionary.

Updating Values

To update the value associated with a specific key, you can use the same assignment operator =:

ages["Alice"] = 31
print(ages)

Output:

{'Alice': 31, 'Bob': 25, 'Charlie': 22, 'David': 35}

Here, we updated the value for the key "Alice" from 30 to 31.

Removing Key-Value Pairs

To remove a key-value pair from a dictionary, you can use the del keyword followed by the key:

del ages["David"]
print(ages)

Output:

{'Alice': 31, 'Bob': 25, 'Charlie': 22}

In this example, we removed the key "David" and its associated value from the ages dictionary.

Iterating Over a Dictionary

You can use a for loop to iterate over the keys, values, or key-value pairs in a dictionary.

Iterating Over Keys

To iterate over the keys in a dictionary, you can use the keys() method:

for key in ages.keys():
    print(key)

Output:

Alice
Bob
Charlie

Note that you can also iterate over the keys by simply using the dictionary itself in the for loop:

for key in ages:
    print(key)

Iterating Over Values

To iterate over the values in a dictionary, you can use the values() method:

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

Output:

31
25
22

Iterating Over Key-Value Pairs

To iterate over the key-value pairs in a dictionary, you can use the items() method:

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

Output:

Alice 31
Bob 25
Charlie 22

In this example, the items() method returns a tuple containing the key and value for each pair, which we then unpack into the variables key and value.

Dictionary Comprehension

Dictionary comprehension is a concise way to create dictionaries using a single line of code. It is similar to list comprehension, but it generates a dictionary instead of a list.

Here is an example of using dictionary comprehension to create a dictionary with the squares of numbers from 1 to 5:

squares = {x: x**2 for x in range(1, 6)}
print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

In this example, the expression x: x**2 creates a key-value pair where the key is the number x and the value is its square. The for x in range(1, 6) part of the comprehension provides the numbers from 1 to 5.

Conclusion

In this blog post, we covered the basics of dictionaries in Python, including creating and modifying dictionaries, accessing values, iterating over dictionaries, and using dictionary comprehension. Dictionaries are an essential data structure in Python, and understanding how to work with them effectively will greatly improve your programming skills.

As you continue to learn programming and work with Python, you'll find that dictionaries are an invaluable tool for organizing and retrieving data efficiently. Keep practicing and experimenting with dictionaries, and soon you'll be able to harness their full potential in your projects.