Python – Adding Items to a Dictionary
Adding New Items to a Dictionary
In Python, dictionaries are dynamic data structures that allow you to store and retrieve data using key-value pairs.
To add a new item to a dictionary, you simply define a new key and assign a corresponding value.
If the key already exists, its value will be updated.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
In the example above, the key "color"
is introduced to the dictionary thisdict
and is assigned the value "red"
.
This simple assignment expands the dictionary without the need for any special methods.
Using update()
to Add or Modify Items
The update()
method in Python serves a dual purpose: it can be used to add new key-value pairs or to update existing ones.
This method accepts either another dictionary or an iterable object that returns key-value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)
Here, the dictionary is updated using the update()
method, where the key "color"
is added with the value "red"
.
If "color"
had already existed, its value would have been replaced. This approach is particularly useful when merging data or handling dynamic key assignments.
For more foundational Python programming tutorials, visit Devyra, where learning is tailored to developers of all levels.