Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make a dictionary in Python

Introduction

Python is a versatile and powerful programming language, loved by both beginners and experienced developers alike. One of the reasons behind its popularity is the fact that Python has an extensive library of built-in data structures, which make coding easier and more efficient. In this article, we will explore one such data structure: the dictionary.

Dictionaries are a collection of key-value pairs, which can be used to store and manage data in a manner that makes it easy to look up and access. In this tutorial, we will explore the basics of dictionaries, including how to create, access, modify, and delete elements, as well as some useful tips and tricks to help you get the most out of this powerful feature.

So, let's dive into the world of Python dictionaries!

What is a Dictionary?

In Python, a dictionary is a mutable, unordered collection of key-value pairs, where each key is unique. In simpler terms, a dictionary can be thought of as a real-life dictionary, where you have words (keys) and their meanings (values). Just as you would look up the meaning of a word in a dictionary, you can look up the value associated with a key in a Python dictionary.

Dictionaries in Python are sometimes referred to as associative arrays, hash tables, or hash maps in other programming languages.

Creating a Dictionary

There are several ways to create a dictionary in Python. We'll discuss three common methods:

  1. Using curly braces ({})
  2. Using the dict() constructor
  3. Using a dictionary comprehension

Method 1: Using Curly Braces

The most straightforward way to create a dictionary is to use curly braces ({}) and separate the keys and values with a colon (:). Here's an example:

my_dict = {"apple": 1, "banana": 2, "orange": 3}
print(my_dict)

Output: {'apple': 1, 'banana': 2, 'orange': 3}

In this example, we created a dictionary called my_dict with three key-value pairs. The keys are the fruit names (strings), and the values are integers.

Method 2: Using the dict() Constructor

Another way to create a dictionary is by using the dict() constructor. This method allows you to create a dictionary by passing in a list of key-value pairs as tuples:

my_dict = dict([("apple", 1), ("banana", 2), ("orange", 3)])
print(my_dict)

Output: {'apple': 1, 'banana': 2, 'orange': 3}

Method 3: Using Dictionary Comprehension

Dictionary comprehension is a concise way to create a dictionary using a single line of code. It is similar to list comprehension but works with dictionaries instead. Here's an example:

my_dict = {x: x**2 for x in range(1, 4)}
print(my_dict)

Output: {1: 1, 2: 4, 3: 9}

In this example, we created a dictionary with keys 1, 2, and 3, and their corresponding values are their squares.

Accessing Dictionary Elements

To access the value associated with a specific key in a dictionary, you can use the square bracket notation ([]) or the get() method.

Using Square Bracket Notation

my_dict = {"apple": 1, "banana": 2, "orange": 3}
print(my_dict["apple"])

Output: 1

In this example, we accessed the value associated with the key "apple" in the my_dict dictionary.

Keep in mind that if you try to access a key that doesn't exist in the dictionary using square bracket notation, Python will raise a KeyError.

Using the get() Method

The get() method allows you to access the value associated with a key without raising a KeyError if the key does not exist. Instead, it returns None or a default value that you can specify.

my_dict = {"apple": 1, "banana": 2, "orange": 3}
print(my_dict.get("apple"))
print(my_dict.get("grapes"))
print(my_dict.get("grapes", "Not found"))

Output:

1
None
Not found

In this example, we used the get() method to access the values associated with the keys "apple" and "grapes". Since the key "grapes" does not exist in the dictionary, the method returns None in the second print statement and the specified default value "Not found" in the third print statement.

Modifying a Dictionary

Dictionaries are mutable, which means that you can add, update, or delete elements after the dictionary has been created.

Adding or Updating Elements

To add a new key-value pair or update the value associated with an existing key, you can use the square bracket notation. If the specified key doesn't exist in the dictionary, a new key-value pair will be added; otherwise, the existing value will be updated.

my_dict = {"apple": 1, "banana": 2, "orange": 3}
my_dict["grapes"] = 4
print(my_dict)

my_dict["apple"] = 5
print(my_dict)

Output:

{'apple': 1, 'banana': 2, 'orange': 3, 'grapes': 4}
{'apple': 5, 'banana': 2, 'orange': 3, 'grapes': 4}

In this example, we first added a new key-value pair "grapes": 4 to the dictionary, and then updated the value associated with the key "apple" to 5.

Deleting Elements

To delete an element from a dictionary, you can use the del keyword followed by the key in square brackets:

my_dict = {"apple": 1, "banana": 2, "orange": 3}
del my_dict["apple"]
print(my_dict)

Output: {'banana': 2, 'orange': 3}

In this example, we deleted the key-value pair with the key "apple" from the dictionary.

Keep in mind that if you try to delete a key that doesn't exist in the dictionary, Python will raise a KeyError. To avoid this, you can check if the key exists in the dictionary before trying to delete it:

my_dict = {"apple": 1, "banana": 2, "orange": 3}
key_to_delete = "grapes"

if key_to_delete in my_dict:
    del my_dict[key_to_delete]
else:
    print(f"{key_to_delete} not found in the dictionary")

Output: grapes not found in the dictionary

Useful Dictionary Methods

Python dictionaries have several built-in methods that can help you work with them more effectively. Here are a few commonly used ones:

  • keys(): Returns a view object displaying a list of all the keys in the dictionary.
  • values(): Returns a view object displaying a list of all the values in the dictionary.
  • items(): Returns a view object displaying a list of all the key-value pairs in the dictionary as tuples.
  • pop(key[, default]): Removes the key-value pair with the specified key and returns the associated value. If the key is not found, it returns the default value if provided; otherwise, it raises a KeyError.
  • clear(): Removes all the elements from the dictionary.

Here's an example demonstrating the use of some of these methods:

my_dict = {"apple": 1, "banana": 2, "orange": 3}

print("Keys:", list(my_dict.keys()))
print("Values:", list(my_dict.values()))
print("Items:", list(my_dict.items()))

value = my_dict.pop("banana", "Not found")
print("Popped value:", value)
print("Dictionary after popping:", my_dict)

my_dict.clear()
print("Dictionary after clearing:", my_dict)

Output:

Keys: ['apple', 'banana', 'orange']
Values: [1, 2, 3]
Items: [('apple', 1), ('banana', 2), ('orange', 3)]
Popped value: 2
Dictionary after popping: {'apple': 1, 'orange': 3}
Dictionary after clearing: {}

Conclusion

In this tutorial, we've explored the basics of working with dictionaries in Python. We've learned how to create, access, modify, and delete elements in a dictionary, as well as some useful built-in methods that can help you work with dictionaries more effectively.

Dictionaries are an incredibly powerful and versatile data structure that you will find yourself using frequently in your Python projects. With a solid understanding of dictionaries, you'll be well-equipped to write efficient and readable code. Happy coding!