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
Frequently Asked:
{'key1': [1, 2, 3, 4, 5]}
Summary
Today, we learned how to add an array to a Python dictionary.