How to add elements to a dictionary in Python?

There are two methods for adding elements to a dictionary.

  1. 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'}
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds