Python Tutorial: Dictionaries
Store data by name instead of position. Dictionaries give every value a meaningful key.
Look things up by name
Lists store values by position: item 0, item 1, item 2. But sometimes position is meaningless — you want to look things up by name.
A dictionary maps keys to values. Country code to country name. User ID to user data. Product name to price. Twelve steps.
What you'll learn in this Python dictionaries tutorial
This interactive Python tutorial has 10 hands-on exercises. Estimated time: 20 minutes.
- Look things up by name — Lists are great for ordered collections. But sometimes order doesn't matter — you just want to look something up by name…
- Create your own dictionary — Create a `product` dictionary with these four keys:
- Adding and updating — Adding or updating a key uses the same syntax:
- get() — safe access — Here's a trap: `dict["key"]` crashes with a `KeyError` if the key doesn't exist.
- pop() and del — removing keys — Two ways to remove a key:
- keys(), values(), items() — loop over everything — Three methods for looping over dictionaries:
- in — key existence check — `in` on a dictionary checks whether a key exists (not a value):
- Nested dictionaries — Dictionary values can be anything — including other dictionaries.
- Dict comprehension — Just like list comprehensions from Chapter 8, Python has dict comprehensions:
- Build a word counter — Final challenge — no starter code.
Python Dictionaries concepts covered
- Look things up by name