Add Elements to Python Dictionary
There are two ways to add elements to a dictionary.
- I am sorry, but I do not have any information on what should be paraphrased. Can you provide the original text that needs to be paraphrased?
my_dict = {'key1': 'value1', 'key2': 'value2'}
# 添加新的键值对
my_dict['key3'] = 'value3'
# 修改已有的键值对
my_dict['key2'] = 'new value2'
print(my_dict)
Output results:
{'key1': 'value1', 'key2': 'new value2', 'key3': 'value3'}
- – Refresh
– Bring up to date
my_dict = {'key1': 'value1', 'key2': 'value2'}
# 添加新的键值对
my_dict.update({'key3': 'value3'})
# 修改已有的键值对
my_dict.update({'key2': 'new value2'})
print(my_dict)
Output result:
{'key1': 'value1', 'key2': 'new value2', 'key3': 'value3'}
You can add new key-value pairs or modify existing ones in the dictionary using any method.