3. Add and update
Dictionaries are mutable: you can add and change pairs after creating one. Assign a value to a key with dictionary[key] = value:
- If the key is not present, the pair is added at the end.
- If the key is present, only its value changes; the position stays the same.
- The key on the left can be any expression that produces a key, such as
scores["wins"].
The right side is an ordinary expression. You can assign a computed value, or update a number in place with an augmented assignment:
Add a new key
Create person = {"name": "Ada"}. Add the key "age" with the value 36 by assigning to person["age"], then print the dictionary.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Update an existing key
Create person = {"name": "Ada"}. Change the value of "name" to "Grace" by assigning to the existing key, then print the dictionary.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Add one to a value
Create scores = {"wins": 2}. Increase the value stored under "wins" by 1 with +=, then print the dictionary.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Add a list as a value
Create an empty dictionary named cart. Add the key "items" with the list ["milk", "bread"] as its value, then print the dictionary.
Print exactly:
Create a free account to save your progress and unlock chapter 2.