Creating and using dicts
A dictionary holds key–value pairs. You write it with curly braces {}, putting a colon between each key and its value.
Creating a dict
Python
Each pair is key: value, and pairs are separated by commas. Keys are usually strings, but values can be any type.
Accessing values
Look up a value by putting its key in square brackets:
Python
If you ask for a key that doesn't exist, Python raises a KeyError.
Adding and updating
Assign to a key to add it (if new) or update it (if it already exists):
Python
Key takeaways
- Create a dict with
{}andkey: valuepairs. - Read a value with
d["key"]. d["key"] = valueadds a new key or updates an existing one.
No comments yet. Add the first comment to start the discussion.