Dictionaries
A dictionary stores data as key-value pairs. Instead of position numbers, you look things up by a meaningful key, like a name or an id. Dictionaries are everywhere: user profiles, settings, counts, and JSON data all use this shape.
What You'll Learn
- Creating dictionaries and reading values
- Adding, updating, and removing keys
- Looping over keys and values
- Safe lookups with
get()
Creating and Reading
Loading Python Playground...
Loading Python Exercise...
Adding and Updating
Assigning to a key that does not exist adds it; assigning to an existing key updates it:
Loading Python Playground...
Loading Python Exercise...
Safe Lookups with get()
Reading a missing key with [ ] raises an error. get() returns None (or a default you choose) instead:
Loading Python Playground...
Looping Over a Dictionary
.items() gives you each key and value together:
Loading Python Playground...
Loading Python Exercise...
Nested Dictionaries
A value can itself be a dictionary, which lets you model richer records, like a contact book:
Loading Python Playground...
Key Takeaways
- Dictionaries use
{key: value}and look up by key - Assign to add or update;
delto remove get()avoids errors on missing keys.items()loops over keys and values together- Values can be dictionaries, for nested records
Quiz
Question 1 of 425% Complete
0 of 4 questions answered

