In Python, you can add a key-value pair to a dictionary (also known as an object) using the square brackets notation or the update() method.
Example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Using square brackets | |
my_dict = {"a": 1, "b": 2} | |
my_dict["c"] = 3 | |
print(my_dict) | |
# Output: {"a": 1, "b": 2, "c": 3} | |
# Using update() method | |
my_dict = {"a": 1, "b": 2} | |
my_dict.update({"c": 3}) | |
print(my_dict) | |
# Output: {"a": 1, "b": 2, "c": 3} |
Note that if the key already exists in the dictionary, the value will be updated with the new value