Python Dictionary: Add Key-Value Pairs

In Python, you can add key-value pairs to a dictionary using the following methods:

  1. By using the assignment operator (=), you can directly assign a value to a key in a dictionary. If the key does not already exist, a new key-value pair will be created. For example:
my_dict = {}  # 创建一个空字典
my_dict['key'] = 'value'  # 添加键值对
print(my_dict)  # 输出: {'key': 'value'}
  1. bring up to date
my_dict = {'key1': 'value1'}
my_dict.update({'key2': 'value2', 'key3': 'value3'})
print(my_dict)  # 输出: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
  1. initialize with default value
my_dict = {'key1': 'value1'}
value = my_dict.setdefault('key2', 'value2')  # 添加新键值对
print(my_dict)  # 输出: {'key1': 'value1', 'key2': 'value2'}
print(value)  # 输出: value2

These are some common methods for adding key-value pairs to a dictionary. Choose the right method based on your specific needs and use case.

bannerAds