Python Dictionary: How to Add Values

To add values to a dictionary, you can either use the assignment operator (=) or the dictionary’s update() method.

Use the assignment operator (=).

my_dict = {}  # 创建一个空字典
my_dict['key1'] = 'value1'  # 向字典中添加键值对
my_dict['key2'] = 'value2'

Utilizing the update() method:

my_dict = {}  # 创建一个空字典
my_dict.update({'key1': 'value1', 'key2': 'value2'})  # 使用字典的update()方法进行添加

If the key to be added already exists in the dictionary, the assignment operator (=) will update the corresponding value, while the update() method will not update the value.

bannerAds