To add an item, simply assign a value to a key the dictionary does not have yet:
Example
Prompt
Write a Python program that creates a dictionary called thisdict with keys "brand", "model", and "year" with values "Ford", "Mustang", and 1964. Then add a new key "color" with value "red" and print the dictionary.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Update Dictionary
Calling update() merges the items of its argument into the dictionary, creating any item that is not there yet.
That argument has to be either a dictionary or an iterable object made up of key:value pairs.
Example
Use update() to give the dictionary a new color item:
Prompt
Write a Python program that creates a dictionary called thisdict with keys "brand", "model", and "year" with values "Ford", "Mustang", and 1964. Then add a new key "color" with value "red" using the update() method and print the dictionary.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)