Learn how to create Python Dictionary | Beginners Guide

Learn how to create Python Dictionary | Beginners Guide

·

11 min read

Play this article

Create your Dev Portfolio today at Fueler.


Welcome to the world of Python dictionaries! Whether you're a beginner looking to get your feet wet or an experienced programmer taking a refresher course, understanding dictionaries is an essential part of learning the language.

So what exactly is a dictionary?

Simply put, a Python dictionary is an unordered collection of key-value pairs. This means that each piece of data has associated with it a key that can be used to access it.

As such, this makes dictionaries incredibly useful for organizing large sets of data in an efficient manner. In Python, dictionaries are used to store data in a way that’s both organized and accessible.

Since data stored in dictionaries is organized into key-value pairs, retrieving or updating this information can be done quickly and easily—without having to remember exact locations or indices within the structure itself.

This makes them easy to use and master for any level of programmer learning Python.

In short, whether you’re dealing with small sets of data or large ones, Python dictionaries will make your life (and working with Python) much easier!

Creating a Dictionary

Creating a dictionary in Python is a simple and effective way to start making your data accessible and usable in your code.

There are a few different ways that you can use to create a dictionary, each one has its strengths and weaknesses.

  1. Using the dictionary constructor to create an empty dictionary: The simplest way to create an empty dictionary is to use the dict() constructor. This method provides you with an empty structure that you can populate with keys and values.
# Create an empty dictionary using the dict() constructor
my_dict = dict()

# Add key-value pairs to the dictionary
my_dict['name'] = 'Rahul'
my_dict['age'] = 18
my_dict['city'] = 'Amsterdam'

# Print the dictionary
print(my_dict) // returns {'name': 'Rahul', 'age': 18, 'city': 'Amsterdam'}
  1. Using curly braces ({}) to create a dictionary with initial values: If you know some of the initial key-value pairs you want in your dictionary, you can use curly braces {} to quickly set up the structure. This method is ideal for quickly creating dictionaries with an initial set of data.
# create a dictionary with initial values using curly braces
car = {'make': 'Jaguar', 'model': 'Ftype', 'year': 2023, 'color': 'maroon'}

# print the dictionary
print(car)
  1. Creating a dictionary with nested dictionaries: If you need more complex structures than simple key-value pairs, then this method will come in handy. It allows you to make nested dictionaries, which is useful when creating complex data structures like graphs or trees.
# Creating a dictionary with nested dictionaries
employees = {
    'John': {
        'position': 'Manager',
        'salary': 100000,
        'team': {
            'Mary': {
                'position': 'Developer',
                'salary': 70000
            },
            'Bob': {
                'position': 'Developer',
                'salary': 65000
            }
        }
    },
    'Alice': {
        'position': 'Director',
        'salary': 150000,
        'team': {
            'Sarah': {
                'position': 'Manager',
                'salary': 120000,
                'team': {
                    'Tom': {
                        'position': 'Developer',
                        'salary': 80000
                    }
                }
            }
        }
    }
}

# Accessing nested dictionary values
print(employees['John']['team']['Mary']['position']) # Output: Developer
print(employees['Alice']['team']['Sarah']['team']['Tom']['salary']) # Output: 80000

Above we have a dictionary called employees that contains nested dictionaries.

The first level of the dictionary contains the names of the employees as keys, and their information (position, salary, and team) as values. The team key of each employee also contains a nested dictionary that contains the information of the employees in their team.

Accessing Dictionary Items

Now that you've created a dictionary, let's look at how you can access the data inside it. To do this, you'll need to use dictionary keys and values.

Retrieving Values Via Keys

The simplest way to access a value in a Python Dictionary is to use the key associated with it. Let's see from an example:

# Create a dictionary
phonebook = {"Rahul": 999999999, "Sunaina": 123456789, "SunainaFather": 456789123}

# Retrieve a value using a key
rahul_phone = phonebook["Rahul"]

# Print the retrieved value
print(rahul_phone)

Above we create a dictionary called phonebook with three key-value pairs. We then use the key "Rahul" to retrieve the associated value (999999999) from the phonebook dictionary and assign it to a variable called rahul_phone.

Finally, we print the value of rahul_phone, which should output 999999999.

Using The Get() Method To Access Dictionary Items Safely

If you're not sure that the item exists in your Python Dictionary, then another option is to use the .get() method. This allows you to safely retrieve items from your dictionary — or, if that item doesn't exist, then it will return None instead of throwing a KeyError.

For example:

# create a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 4}

# using the get() method
apple_count = my_dict.get('apple')
pear_count = my_dict.get('pear')

# print the results
print(apple_count)  # Output: 2
print(pear_count)   # Output: None

Above we have a dictionary my_dict with the key-value pairs {'apple': 2, 'banana': 3, 'orange': 4}.

We then use the get() method to safely retrieve the value associated with the key 'apple' and 'pear'. The value associated with 'apple' is 2, so apple_count is assigned the value 2. The key 'pear' is not in the dictionary, so pear_count is assigned the value None.

Handling KeyError Exceptions

When accessing dictionary items in Python, it's important to handle the possibility of a KeyError exception. This occurs when a key is not found in the dictionary. Let's understand this from a short example.

# Creating a dictionary with key-value pairs
my_dict = {"apple": 1, "banana": 2, "orange": 3}

# Retrieving a value using a non-existent key
try:
    value = my_dict["grape"]
except KeyError:
    print("The key 'grape' does not exist in the dictionary")

Above we are trying to retrieve a value from the my_dict dictionary using the key 'grape'. However, since this key doesn't exist in the dictionary, a KeyError exception will be raised.

To handle this exception, we can use a try-except block. The try block contains the code that may raise an exception, while the except block specifies how to handle the exception.

In this case, we are catching the KeyError exception and printing a message to inform the user that the key doesn't exist in the dictionary.

Modifying Dictionary Items

Another important part of working with dictionaries is knowing how to modify existing items in them. On the surface, this might seem pretty simple—you just add it back in with a new value, right? Well, it's a bit more complex than that.

A great way to get started is by first learning the syntax: it requires brackets and quotation marks at certain points.

# Creating a dictionary with some initial values
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Modifying an existing item in the dictionary
my_dict['age'] = 26

# Printing the updated dictionary
print(my_dict)

Above we first create a dictionary called my_dict with some initial key-value pairs. We then modify the value of the 'age' key to 26 by accessing it using the brackets and assigning the new value to it.

It's important to note that if the key you're trying to modify doesn't already exist in the dictionary, the above approach will create a new key-value pair. If you don't want that to happen, you can use the update() method to modify existing items or add new ones.

# Creating a dictionary with some initial values
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Modifying an existing item or adding a new one using the update() method
my_dict.update({'age': 26, 'gender': 'female'})

# Printing the updated dictionary
print(my_dict)

Here we use the update() method to modify the value of the 'age' key to 26 and add a new key-value pair for 'gender'. Note that the update() method takes a dictionary as an argument, and any matching keys in the dictionary will be updated with their corresponding values.

Modifying items in an existing dictionary requires some code literacy and trial and error, but once you have the syntax down, you'll be able to edit your dictionaries like a pro!

Dictionary Methods and Operations

Let's now look at some useful dictionary methods and operations.

len()

The len() function is great for finding out the length of a dictionary, that is, the number of items in a dictionary. You can use this to see how many items your dictionary contains. In short, a simple len() statement will display how many keys and values are stored within your dictionary!

my_dict = {'apple': 2, 'banana': 3, 'orange': 1, 'pear': 4}

# Finding the length of the dictionary
length = len(my_dict)

print("The dictionary contains", length, "items.")

So here the len() function will return the number of key-value pairs in the dictionary, which is 4 in this case.


Read More - A Step-by-Step Guide to Comment Blocking in Python


Checking if a key exists using the in keyword

The in keyword can be used to check if a key exists in a given Python Dictionary. Let's see a small example:

# Create a dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 4}

# Check if a key exists using the in keyword
if "apple" in my_dict:
    print("The key 'apple' exists in the dictionary!")
else:
    print("The key 'apple' does not exist in the dictionary.")

In this example, we create a dictionary called my_dict with three key-value pairs. We then use the in keyword to check if the key "apple" exists in the dictionary. Since "apple" is a key in the dictionary, the output will be: The key 'apple' exists in the dictionary!.

If the key you are looking for does exist, then anything within the if statement will execute; otherwise, nothing happens—it's as simple as that!

Retrieving all Keys and Values of a Dictionary

You can retrieve all keys and values of a dictionary with two built-in functions: dict.keys(), which shows the keys to your dictionary; and dict.values(), which returns all values of the given Python Dictionary.

What's more, you can find out both keys and values by using the dict.items() method!

# Create a dictionary with some key-value pairs
my_dict = {'apple': 2, 'banana': 3, 'orange': 4}

# Retrieve all keys and values of the dictionary using the items() method
for key, value in my_dict.items():
    print(f'{key}: {value}')

Above we create a dictionary my_dict with some key-value pairs. We then use the items() method to retrieve all the keys and values of the dictionary, and iterate through them using a for loop. Inside the loop, we print out each key and its corresponding value using string formatting.

Updating and Merging Dictionaries

Updating an existing Python Dictionary with new data is easy—simply use the update() method, which takes two parameters: one that contains all keys and values from another dictionary (the source) and another that points to an existing dictionary (the target).

# Updating a dictionary
dict1 = {'name': 'John', 'age': 30}
dict2 = {'age': 35, 'city': 'New York'}
dict1.update(dict2)
print(dict1)
# Output: {'name': 'John', 'age': 35, 'city': 'New York'}

# Merging two dictionaries
dict3 = {'name': 'Alice', 'gender': 'Female'}
dict4 = {'age': 25, 'city': 'Chicago'}
merged_dict = {**dict3, **dict4}
print(merged_dict)
# Output: {'name': 'Alice', 'gender': 'Female', 'age': 25, 'city': 'Chicago'

In the above example, we have two dictionaries dict1 and dict2. We update dict1 with the contents of dict2 using the update() method. This changes the value of the 'age' key in dict1 to 35 and adds the 'city' key with the value 'New York' to dict1.

Next, we have two dictionaries dict3 and dict4. We merge these dictionaries into a new dictionary merged_dict using the {**dict1, **dict2} syntax, which combines the key-value pairs from both dictionaries into a single dictionary.

You're getting it right? Just take time to understand, it can be a bit confusing but when you get it, it's easy.

Iterating Through a Dictionary

Using a for loop to iterate through a dictionary

You can also use a for loop to iterate through a dictionary. A for loop is another way of repeating an action or set of actions over and over again. It's like a robotic machine, where you give it instructions and it will simply follow them.

Basically, what you do is tell the loop to go through each value in your dictionary, one at a time, and then execute the instructions that you have given it. It will stop when it reaches the end of your dictionary. Here's an example:


# Create a dictionary of fruits and their colors

fruits = {"apple": "red", "banana": "yellow", "grape": "purple"}

# Loop through the keys and values of the dictionary

for fruit, color in fruits.items():

print(f"The {fruit} is {color}")

# Output:
# The apple is red
# The banana is yellow
# The grape is purple

In this example, we first create a dictionary called fruits that contains the names of different fruits as keys and their corresponding colors as values.

Then, we use a for loop to iterate through the keys and values of the fruits dictionary using the items() method. Inside the loop, we assign the key to the variable fruit and the value to the variable color.

Finally, we use the print() function to display a message for each fruit and its corresponding color. The loop will stop when it reaches the end of the fruits dictionary.

Pretty cool right? Iterating with a for loop is just one of many ways to work with dictionaries in Python—there's plenty of other methods that you can explore!

items() method

item() method is used to retrieving keys and values. Let's see a simple example for this:

Suppose we have a dictionary that contains the names and ages of some individuals as key-value pairs. We can use the items() method to iterate through the dictionary and retrieve the name and age of each person as a pair.

# Creating a dictionary with names and ages of individuals
ages = {"Alice": 30, "Bob": 25, "Charlie": 35}

# Iterating through the dictionary using the items() method
for name, age in ages.items():
    print(name, "is", age, "years old")
#The output
Alice is 30 years old
Bob is 25 years old
Charlie is 35 years old

Conclusion

In conclusion, Python dictionaries make it easy to manage complex data. They're a powerful tool for data manipulation, and a great way to store and access information. With this beginner's guide, you now have the information you need to start using Python dictionaries for yourself.

You'll be able to create, modify, and iterate over dictionaries with ease. Go ahead and get started now—you'll be glad you did.


Create your Dev Portfolio today at Fueler.

Did you find this article valuable?

Support Fueler Blog by becoming a sponsor. Any amount is appreciated!