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.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.