How to Easily Add Key-Value Pairs to an Existing Dictionary
You can add a new key-value pair to an existing dictionary in Python using the assignment operator (=
) or the update()
method. Here are five examples demonstrating both methods:
- Using the assignment operator:
# Existing dictionary
my_dict = {'a': 1, 'b': 2}
# Adding a new key-value pair
my_dict['c'] = 3
print(my_dict)
# Output: {'a': 1, 'b': 2, 'c': 3}
- Using the
update()
method:
# Existing dictionary
my_dict = {'a': 1, 'b': 2}
# Adding a new key-value pair
my_dict.update({'c': 3})
print(my_dict)
# Output: {'a': 1, 'b': 2, 'c': 3}
- Using the
update()
method with keyword arguments:
# Existing dictionary
my_dict = {'a': 1, 'b': 2}
# Adding a new key-value pair
my_dict.update(c=3)
print(my_dict)
# Output: {'a': 1, 'b': 2, 'c': 3}
- Using the
dict()
constructor with keyword arguments:
# Existing dictionary
my_dict = {'a': 1, 'b': 2}
# Adding a new key-value pair
my_dict = dict(my_dict, c=3)
print(my_dict)
# Output: {'a': 1, 'b': 2, 'c': 3}
- Using a dictionary comprehension:
# Existing dictionary
my_dict = {'a': 1, 'b': 2}
# Adding a new key-value pair
new_key, new_value = 'c', 3
my_dict = {**my_dict, new_key: new_value}
print(my_dict)
# Output: {'a': 1, 'b': 2, 'c': 3}
All these methods will add a new key-value pair to the existing dictionary.