Lesson 51 +10 XP

Change, Add, and Remove Dictionary Items

Dictionaries are fully changeable.

Change a value


python
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict["year"] = 2018
print(thisdict["year"])

### 2018

Update with update()


python
thisdict.update({"year": 2020, "color": "red"})

update() changes existing keys and adds new ones.

Add a new item

Just assign a new key:


python
thisdict["color"] = "red"
print(thisdict)

### ... 'color': 'red'

Same syntax as changing; a new key adds, an existing key updates.

Remove with pop


python
thisdict.pop("model")

### removes and returns the value

Remove with popitem


python
thisdict.popitem()

### removes the last inserted item

Remove with del


python
del thisdict["year"]
del thisdict

### deletes the whole dictionary

Clear with clear


python
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, and clear() remove items.
  • Same assignment syntax adds or updates.