Everyday dictionary operations
Change a key name in one of the lookups to see KeyError, then use get to avoid it.
A dictionary stores pairs: each key leads to a value, and you look a value up by its key instead of by position. Dictionaries keep the order in which keys were added (guaranteed since Python 3.7) and are the shape of almost all JSON data.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Make a dictionary student = {"name": "Asha", "age": 21}. Add "city": "Delhi", change age to 22, then print every key and value as key: value.
Given marks = {"maths": 80, "science": 90}, print the mark for "english" as 0 if it is missing, without raising an error.
Count how many times each word appears in "to be or not to be" and print the dictionary.
Explain it without notes
How is a dictionary different from a list, and when do you use each?
What is the difference between d[key] and d.get(key)?
Does a dictionary keep order? Since which version?
How do you loop over the keys and values of a dictionary together?
What are the ways to merge two dictionaries, and what does "the right-hand value wins" mean for nested dictionaries?
Expected output
apple: 30
kiwi (get): None
kiwi (get with default): 0
'apple' in prices: True
30 in prices: False
after changes: {'apple': 35, 'kiwi': 40} | removed: 50
final: {'apple': 35, 'kiwi': 45, 'grape': 60, 'plum': 20} | entries: 4
apple costs 35
kiwi costs 45
grape costs 60
plum costs 20
keys: ['apple', 'kiwi', 'grape', 'plum']
values: [35, 45, 60, 20]