Concept
Adding & Updating Keys
Assign to a key with `d[key] = val`. If the key exists, it overwrites the old value. If it's new, it creates it.
python
profile = {"user": "neo"}
profile["user"] = "trinity" # Overwrite
profile["level"] = 99 # New key created
print(profile)
# 81. Adding & Updating Keys Assign to a key with `d[key] = val`. If the key exists, it overwrites the old value. If it's new, it creates it: ```python profile = {"user": "neo"} profile["user"] = "trinity" # Overwrite profile["level"] = 99 # New key created print(profile) ``` Dictionaries in Python 3.7+ remember insertion order. When you add a new key, it stays at the end of the dictionary instead of jumbling around.
Checkpoint
What happens if you assign `d['score'] = 100` when `'score'` already exists in `d`?
Practice
Start with `state = {"health": 50}`. Update `"health"` to `100`, add `"shield"` with value `25`, and print `state`.
01
Tap code blocks below to assemble
Available Blocks