Add Key-Value Pairs to Python Dictionary
To add key-value pairs to a Python dictionary, you can use the following method:
- Add key-value pairs using index operator []:
my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
print(my_dict)
- Add a key-value pair or multiple key-value pairs using the update() method.
my_dict = {}
my_dict.update({'key1': 'value1', 'key2': 'value2'})
print(my_dict)
- Use the setdefault() method to add a key-value pair – if the key does not exist, it will be added, but if it already exists, no action will be taken.
my_dict = {}
my_dict.setdefault('key1', 'value1')
my_dict.setdefault('key2', 'value2')
print(my_dict)
There are several ways to add key-value pairs, the method you choose depends on your needs and habits.