Add a list to a Python Dictionary

This tutorial will discuss how to add a list to a Python dictionary.

We can add a list into a dictionary as the value field.

Suppose we have an empty dictionary, like this,

# Create an empty dictionary
my_dict = {}

Now, we are going to add a new key-value pair into this dictionary using the square brackets. For this, we will pass the key into the square brackets and assign the list as a value field for this key-value pair.

# Define the list to add
my_list = [1, 2, 3, 4, 5]

# Add the list to the dictionary
my_dict["key1"] = my_list

This will add the new key-value pair into the dictionary, where the list is the value field. Now suppose we want to add more values into the list in the value field for this key. For this, we will select the value associated with the key using the square brackets. By passing the key in the square brackets, it will return the reference to the list that is linked with the given key. Then, we will call the extend method on the list to add more values into it. Like this,

# Add more elements in the value lits
my_dict["key1"].extend([11, 22, 33])

So basically, it will add three more values into the existing value field of the key-value pair. We can confirm this by printing the dictionary.

Let’s see the complete example,

# Create an empty dictionary
my_dict = {}

# Define the list to add
my_list = [1, 2, 3, 4, 5]

# Add the list to the dictionary
my_dict["key1"] = my_list

# Print the updated dictionary
print(my_dict)

# Add more elements in the value lits
my_dict["key1"].extend([11, 22, 33])

# Print the updated dictionary
print(my_dict)

Output

{'key1': [1, 2, 3, 4, 5]}
{'key1': [1, 2, 3, 4, 5, 11, 22, 33]}

Summary

Today, we learned how to add a list to a Python dictionary.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top