Adding Items to a Dictionary in Python: A Simple Guide
Discover how to add new items to a Python dictionary by using a new key and assigning a value. This guide provides clear examples to show how you can easily update dictionaries with additional entries.
Add Dictionary Items
Adding an item to a dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict["color"])
Output
red
Update Dictionary
The update()
method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}