my_dict = { "key1": "value1" } # Add a new key-value pair to the dictionary my_dict["key2"] = "value2"
To add a new key to a dictionary in Python, you can use square bracket notation to specify the new key and assign a value to it.
Alternatively, you can use the update() method to add multiple key-value pairs to a dictionary at once. For example:my_dict = { "key1": "value1" } # Add two new key-value pairs to the dictionary my_dict.update({"key2": "value2", "key3": "value3"})
Both of these methods will add the new key-value pairs to the dictionary, unless a key with the same name already exists in the dictionary, in which case it will be overwritten with the new value.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.