How to add data to a key in Python?

In Python, you can use a dictionary to store data and access or manipulate it using keys. To add data to a specific key in the dictionary, you can use the following method:

  1. Using the assignment operator (=) directly assigns a value to a specific key, creating a new key-value pair if the key does not exist.
my_dict = {}  # 创建一个空字典
my_dict["key1"] = "value1"  # 向字典中添加数据到特定键中
  1. make changes to
my_dict = {"key1": "value1"}
new_data = {"key2": "value2", "key3": "value3"}
my_dict.update(new_data)  # 向字典中添加数据

Please note that if the new key already exists in the dictionary, the corresponding value will be updated to the new value. If the key does not exist in the original dictionary, a new key-value pair will be added.

I hope this helps you!

广告
Closing in 10 seconds
bannerAds