PY-101 ยท Collections
Dictionaries
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A dictionary stores values under unique keys, written as {"name": "Asha", "age": 29}. You read a value with its key, d["name"], and add or update with d[key] = value. It is the right tool whenever you look things up by a name instead of a position.
- Create and read a dict
- Add and update keys
- Use get() and items()
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
stock = {"tea": 12, "milk": 5}stock["bread"] = 8stock["milk"] = stock["milk"] - 2print(stock)print("Coffee:", stock.get("coffee", 0))for item, qty in stock.items():print(item, qty)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
{'tea': 12, 'milk': 3, 'bread': 8}
Coffee: 0
tea 12
milk 3
bread 8 ๐ฏ Count how many times each fruit appears in basket using a dictionary and get(). Print the dictionary.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
for f in basket: counts[f] = counts.get(f, 0) + 1
- The problemA phone book: you never ask for "the 427th entry". You ask for "Ravi" and get his number. That is exactly what a dictionary does.
- The Python idea
d = {key: value}A dictionary stores values under unique keys, written as {"name": "Asha", "age": 29}. - In real lifeEvery web API response you read in Python (weather, payments, maps) arrives as JSON and becomes a dictionary.
Start with a question
A phone book: you never ask for "the 427th entry". You ask for "Ravi" and get his number. That is exactly what a dictionary does.
JSON from APIs, settings, user profiles and counters are all dictionaries. Real Python code is full of them.
Explain it like I'm 10
A dictionary is a set of labelled drawers. To find something you read the label, not count the drawers.
The technical explanation
Keys are usually strings or numbers and must be unique. Values can be anything, even lists or other dicts.
d[key] = value adds a new key or replaces the old value.
for key, value in d.items(): loops over both. d.keys() and d.values() give each side.
Syntax
d = {key: value}
d[key] = value
d.get(key, default) Real-world scenario
Every web API response you read in Python (weather, payments, maps) arrives as JSON and becomes a dictionary.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Comprehensions โQuestions people ask
Are Python dictionaries ordered?
Yes. Since Python 3.7 dictionaries keep the order in which keys were added.
How do I check if a key exists in a dictionary?
Use if key in d:. It checks keys, not values.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner Are Python dictionaries ordered?
Yes. Since Python 3.7 dictionaries keep the order in which keys were added.
beginner How do I check if a key exists in a dictionary?
Use if key in d:. It checks keys, not values.
intermediate d = {"a": 1}. What is d["a"]?
1. The key "a" holds 1.
intermediate What does d.get("z", 0) return when "z" is missing?
0. get returns the default.
Quick revision
Remember
- Create and read a dict
- Add and update keys
- Use get() and items()
d["missing"]raises KeyError.d.get("missing", 0)returns 0 instead, which is perfect for counting.
Syntax
d = {key: value}
d[key] = value
d.get(key, default) Official documentation
- Dictionaries (docs.python.org)