Python 3.12 ยท
โ verified by execution on 2026-07-23
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type
python
tel = {'jack': 4098, 'sape': 4139}tel['guido'] = 4127print(tel['jack'])
Output
4098
Your output
Dictionary Constructors
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
python
print(dict([('sape', 4139), ('guido', 4127)]))
Output
{'sape': 4139, 'guido': 4127}
Your output
Deleting Items
It is also possible to delete a key:value pair with del.
python
tel = {'jack': 4098, 'sape': 4139}del tel['sape']print(list(tel))
Output
['jack']
Your output
Missing Keys
It is an error to extract a value using a non-existent key.
python
tel = {'jack': 4098}try: print(tel['guido'])except KeyError as e: print(repr(e))
Output
KeyError('guido')
Your output
To prevent this error, you can use the .get() method.
python
tel = {'jack': 4098}print(tel.get('guido', 'Not Found'))
Output
Not Found
Your output
Dictionary Iteration
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
python ยท visualize
knights = {'gallahad': 'the pure', 'robin': 'the brave'}for k, v in knights.items(): print(k, v)
Check yourself
Lists can be used as keys in a dictionary.
Reveal answer
Lists are mutable and therefore cannot be used as dictionary keys. Attempting to do so raises a TypeError. โ Lists are mutable and therefore cannot be used as dictionary keys. Attempting to do so raises a TypeError.
Iterating over a dictionary directly with 'for item in my_dict' returns the values.
Reveal answer
Iterating over a dictionary directly yields its keys, not its values. โ Iterating over a dictionary directly yields its keys, not its values.
Dictionaries in Python 3.12 are unordered.
Reveal answer
Since Python 3.7, dictionaries formally preserve the insertion order of their keys. โ Since Python 3.7, dictionaries formally preserve the insertion order of their keys.
Challenges
Challenge 1 +15 XP
Write a function count_words(words) that takes a list of strings and returns a dictionary where keys are words and values are the number of times they appear.
python
Test 1 โ expects "{'apple': 2, 'banana': 1} \n"
Need a hint? (โ25% XP)
Use .get(word, 0) to fetch the current count or 0 if it doesn't exist, then add 1.
Show solution (0 XP)
def count_words(words): counts = {} for word in words: counts[word] = counts.get(word, 0) + 1 return countsprint(count_words(['apple', 'banana', 'apple']))
Challenge 2 +15 XP
Write a function merge_profiles(p1, p2) that takes two dictionaries and returns a new dictionary combining both. If keys overlap, p2 should win.
python
Test 1 โ expects "{'name': 'jack', 'age': 40} \n"
Need a hint? (โ25% XP)
Copy the first dictionary, then .update() it with the second.
Two Devices, No Server, No Conflicts: How Local-First Apps Merge โ Apps that work offline and reconcile afterwards need a merge that no server arbitrates. Edit two devices here, predict the merged result, and find out why the answer is usually a list neither device was holding.
More Buckets Will Not Save a Bad Hash Function โ Hash tables are called O(1) so often that the condition gets dropped. Change the hash function here, drag the table from 4 buckets to 16, and watch the longest chain refuse to move - because memory cannot fix a hash that ignores its input.
Breadth-First and Depth-First Are the Same Loop, One Line Apart โ BFS and DFS get taught as two algorithms because one is usually written with a queue and the other with recursion. Run both here from one shared loop, changing only which end of the frontier the next node comes from, and watch the paths diverge.
List or Matrix? Guess Before You Look, and Watch the Answer Flip โ Lists for sparse graphs, matrices for dense ones is true enough to repeat and too vague to use. Predict the winner here on two dials - density and question mix - and find out how often the rule of thumb is wrong.
Play the Cache: Why LRU Sometimes Scores Zero โ A cache has to decide what to throw away before it knows what will be asked for next. Take the eviction decision yourself here, scored live against LRU and against the best any policy could possibly do.
Find the Wasted Calls: the Skill Behind Every Memoisation โ Memoisation is easy to explain and hard to apply, because the difficult part is noticing that a subproblem repeats at all. Here the recursion tree is drawn and you have to find the repeats yourself, scored, with wrong clicks counted.
A Structure That Is Allowed to Be Wrong, in One Direction Only โ A Bloom filter answers have I seen this before without storing anything it has seen - and sometimes says yes about a word it has never met. Hunt for one of those false positives here, then look at exactly which bits caused it.
Pick the Structure: Ten Requirements, and Nobody Tells You the Answer โ Every other page here takes one structure apart. This one starts where real work starts - with a requirement that never names the structure. Ten jobs, four candidates each, and the wrong answers are the ones people reach for by habit.
How Embeddings Work, Counted by Hand โ An embedding turns a word into numbers so that similar words land near each other. Build real word vectors from your own text, see why cat and dog score alike without ever appearing together, and why similarity is measured by angle rather than distance.
What Is a Token? Train a Tokenizer and Watch One Form โ Language models read tokens, not letters or words. Train a real byte-pair encoding tokenizer on your own text, watch the vocabulary build itself merge by merge, and see why models struggle to spell.