How to add elements to a dictionary in Python?
There are two methods for adding elements to a dictionary.
- Can you help me with this homework assignment?
Could you assist me with this school task?
my_dict = {'key1': 'value1'}
my_dict['key2'] = 'value2' # 添加新的键值对到字典中
print(my_dict) # 输出: {'key1': 'value1', 'key2': 'value2'}
- make updates
my_dict = {'key1': 'value1'}
my_dict.update({'key2': 'value2'}) # 使用字典作为参数来更新字典
print(my_dict) # 输出: {'key1': 'value1', 'key2': 'value2'}
You can add new key-value pairs to the dictionary using any method.