Python Change Dictionary Items
Dictionaries are mutable, so you can update existing values, add brand-new pairs, and remove entries at any time.
Updating an existing value
Assigning to a key that already exists replaces its value. If the key is not there yet, the same syntax adds it, so one statement can either update or create depending on whether the key was present.
Change and add with brackets
book = {"title": "Dune", "pages": 412}
book["pages"] = 688 # update existing key
book["author"] = "Herbert" # add a new key
print(book)The update() method
The update() method merges another dictionary (or key-value pairs) into the current one. Matching keys are overwritten and new keys are appended, which is convenient for applying several changes at once.
Merging changes
book = {"title": "Dune", "pages": 412}
book.update({"pages": 688, "year": 1965})
print(book)Removing items
Different ways to remove
book = {"title": "Dune", "pages": 688, "year": 1965}
removed = book.pop("year")
print(removed) # 1965
del book["pages"]
print(book) # {'title': 'Dune'}Note: Using del on a key that does not exist raises KeyError, and popitem() on an empty dictionary raises KeyError. Check with 'in' first if you are unsure.
- Assignment updates a key if it exists, or creates it if it does not.
- update() applies many changes at once.
- pop() returns the removed value; del simply deletes.
- clear() leaves you with an empty but still usable dictionary.