Add an Array to a Python Dictionary

This tutorial will discuss how to add an array to a Python dictionary.

Suppose we have an array like this,

my_array = [1, 2, 3, 4, 5]

Now we want to add this array into the dictionary as a value field. For this, first, we create an empty dictionary.

# Create an empty dictionary
my_dict = {}

Now, we will add a new key-value pair into the dictionary using the square brackets. In the square brackets, we will pass the key and assign the array as the value.

# Add the array to the dictionary
my_dict["key1"] = my_array

So, it will add the key-value pair into the dictionary where the given array is the value field.

Let’s see the complete example,

# Create an empty dictionary
my_dict = {}

# Define the array to add
my_array = [1, 2, 3, 4, 5]

# Add the array to the dictionary
my_dict["key1"] = my_array

# Print the updated dictionary
print(my_dict)

Output

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

Summary

Today, we learned how to add an array 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