Loading lessons...
Change, Add, and Remove Dictionary Items
Change, Add, and Remove Dictionary Items
Dictionaries are fully changeable.
Change a value
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict["year"] = 2018
print(thisdict["year"]) # 2018
Update with update()
thisdict.update({"year": 2020, "color": "red"})
update() changes existing keys and adds new ones.
Add a new item
Just assign a new key:
thisdict["color"] = "red"
print(thisdict) # ... 'color': 'red'
Same syntax as changing; a new key adds, an existing key updates.
Remove with pop
thisdict.pop("model") # removes and returns the value
Remove with popitem
thisdict.popitem() # removes the last inserted item
Remove with del
del thisdict["year"]
del thisdict # deletes the whole dictionary
Clear with clear
thisdict.clear() # empties the dictionary
TL;DR
- Assign to a key to change or add.
update()merges changes from another dict.pop(key),popitem(),del, andclear()remove items.- Same assignment syntax adds or updates.