Lesson 4 of 146 min
Dicts and functions
A dict finds a value by its key; a function does one job when it is called, and a comprehension does it for every item of a list.
After this lesson you can read and write dicts, functions and comprehensions.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Every key and its value
.items() gives a dict's pairs one at a time, so a for loop can take the key and the value together. The f before the quotes lets you put a name inside curly brackets, and Python writes its value there.
vocab = {"cat": 0, "ran": 1, "the": 2}
for word, number in vocab.items():
print(f"{word} is {number}")cat is 0 ran is 1 the is 2
An input with a value of its own
A function's input can have a value it uses when the call leaves it out. Here unknown is 3 unless the call names another. You will see this all through AI code, as in test_size=0.2: the name, an equals sign, the value.
vocab = {"cat": 0, "ran": 1, "the": 2}
def encode(word, unknown=3):
return vocab.get(word, unknown)
print(encode("the"))
print(encode("dog"))
print(encode("dog", unknown=-1))2 3 -1
Make the vocabulary from a list
Real code doesn't type the vocabulary by hand. enumerate gives each item with its position, and a comprehension in curly brackets makes a dict: the key, a colon, then the value.
words = ["cat", "ran", "the"]
vocab = {word: i for i, word in enumerate(words)}
print(vocab){'cat': 0, 'ran': 1, 'the': 2}Keep only some of them
A comprehension can end with an if, and then it keeps only the items for which the test is True. word in vocab is True when the dict holds that key. This is the first choice from the video's question: dog is left out, and nobody sees the gap.
vocab = {"cat": 0, "ran": 1, "the": 2}
words = "the dog ran".split()
known = [word for word in words if word in vocab]
print(known)
print([vocab[word] for word in known])['the', 'ran'] [2, 1]
Run on Python 3.13.3. Checked on .
Quiz
Two questions on this lesson. Answer as often as you like.
1 of 2
vocab = {"cat": 0, "ran": 1, "the": 2}, and encode returns vocab[word]. What happens when you call encode("dog")?
2 of 2
What does this print?
vocab = {"cat": 0, "ran": 1, "the": 2}
def encode(word):
return vocab[word]
ids = [encode(word) for word in ["ran", "the", "cat"]]
print(ids)The ideas in this lesson
- Dicts
- A dict keeps values under keys, and finds a value by its key, not by a position.
- Functions
- `def` gives a name to some code. A call runs it with its input, and `return` sends the answer back.
- Comprehensions
- A comprehension makes a list in one line: first what to make, then a for loop's part.
- A missing key
- A dict stops with a KeyError when asked for a key it does not hold. `get` gives a value you choose instead.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Words into numbers
Here's a question. A language model never reads words. It reads numbers. Eight lines of Python can do the same, for a few words. Each word gets its own number. Now the sentence has a word it doesn't know. Look, there's no number for dog. What will Python do? Leave dog out, put nothing in its place, or stop?
A dict
Keep your guess. By the end, you'll read all eight lines. In this small vocabulary, cat is zero, ran is one, and the is two. So "the cat ran" becomes two, zero, one. But how does the code know that cat is zero?
Line one makes a dict. Each word is a key. Beside it is its number: its value. Like a dictionary, with a word and what it means.
Ask for "cat". You get zero. A dict finds a value by its key, not by its place.
Split makes a list
And how do the words come out of the sentence? Split comes with every piece of text. You write it after a dot. It cuts the text at its spaces, into a list: the words, in the order they came.
As in any list, position zero holds "the".
Your turn
Your turn. Which word is at position one?
And what number does the dict give "the"?
Position one is "cat", the second word. And the dict gives "the"... two.
A list, by position. A dict, by key.
def
What does def do, when Python reaches it? Lines four and five make a function, called encode. Python reads def, and keeps encode in its memory. That's the same memory every cell shares. Then it moves on. Look: line five didn't run. It waits.
A call
So when does line five run? When something calls encode. Line seven calls it the way you call any function: its name, then brackets with its input. The input is the first word, "the". The mark jumps up to line five, and there, word is "the".
The dict is in the memory too, so line five can read it. The dict gives two. And return sends that two back, to line seven.
A call goes in with a word, and comes back with a number.
The long way
Line seven calls encode once for every word. Three calls, in one line.
How? First, the long way: a for loop.
Start with an empty list. Then, for each word in words, append adds its number at the end. Append comes with every list, after a dot. The indented line runs once for each word.
At the end, what will the list hold?
It runs three times. "The", then "cat", then "ran". And the list grows: two... two, zero... two, zero, one.
If you said zero, one, two, those are the dict's numbers, from top to bottom. But the list follows the sentence.
A comprehension
Now the short way. The three lines become one: line seven. Inside square brackets, the loop's last line comes first: encode of word. That's what to make. Then comes the "for" part: for word in words.
So to read it, start at the "for". For each word in words... make encode of word.
Line seven runs... two, zero, one. The same list, in one line. That's a comprehension.
A word it doesn't know
Back to the question from the start. The dict holds cat, ran and the. And now, line two says "the dog ran". You can read every line now.
Will Python leave dog out? Put nothing in its place? Or stop?
KeyError
It stops. On line five, at the second word.
Key error, dog. Those are Python's own words: the key it couldn't find. A dict finds a value only under a key it holds. This dict has no dog.
If you said "nothing in its place", some languages do that. Then the program goes on, with a gap nobody sees. A Python dict stops, so you see the missing word at once.
get
So how does dog get a number?
Line five changes to get. Like split, get comes after a dot: it comes with every dict. Here it takes two inputs: the word, and the number three. Get gives the word's number when the key is there... and three when it is not.
Run it. Two, three, one. Here, three means "a word I don't know".
Real models
So what do real models do with a word they have never seen? GPT-2's vocabulary is a dict just like this one... with more than fifty thousand keys. Many of them are pieces of words.
So a word it doesn't know is split into pieces it does know. "Unbelievable" becomes four pieces. No stop. And no single number for every unknown word.
By key
So here's what you saw. A dict finds a value by its key. A function does one job, and gives back a value. And a comprehension does it for every word.
Each word, its number
So a dict and a function turn words into numbers. Now try it on this lesson's page, and take the quiz. Make dog come out as nothing at all. Find another way to look it up.
You use this lesson in Lab 2: A tiny tokenizer, after Classes, just enough.
Facts last checked on .
