2

Add a list to a Python Dictionary

 1 year ago
source link: https://thispointer.com/add-a-list-to-a-python-dictionary/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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,

Copy to clipboard
# Create an empty dictionary
my_dict = {}
# 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.

Copy to clipboard
# Define the list to add
my_list = [1, 2, 3, 4, 5]
# Add the list to the dictionary
my_dict["key1"] = my_list
# 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,

Copy to clipboard
# Add more elements in the value lits
my_dict["key1"].extend([11, 22, 33])
# 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,

Copy to clipboard
# 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)
# 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

Copy to clipboard
{'key1': [1, 2, 3, 4, 5]}
{'key1': [1, 2, 3, 4, 5, 11, 22, 33]}
{'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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK