Boxes you find by name: key and value
Arrays let you grab things by position (lesson 8). But sometimes you want to find things by name, not a number. When you look up a friend's phone number, you think 'Minsu', not 'the 47th contact'. Let's see how a name tag pulls it out instantly.
A name tag, not a number
The arrays in lesson 8 were boxes in a row.
Box 1, 2, 3... grabbed by position.
But when you look up a word in a dictionary,
you don't think of 'the 325th word'.
You just open to 'apple' and the meaning is there.
Key and value find things by a name tag like that.
Pick a name. You get its value straight away, no position needed.
No counting positions.
Know the name, and you reach the value right away.
So how exactly does this 'name tag and contents'
get paired up?
Pairing up: key and value
Each slot is always a pair of two.
A name tag (the key) and the contents inside (the value).
Like 'apple'(key) -> 'a fruit'(value),
or 'Minsu'(key) -> '010-1234'(value).
Call the key, and its paired value comes out.
Connect a key to a value. Once bound, they're one 'key -> value' pair.
The key is the name that tells you 'where to find it',
and the value is 'what's actually stored'.
A whole pile of these pairs is a dictionary.
But with many pairs, how do you find the one you want fast?
No searching down the line
Even with a thousand values,
key and value don't scan from the start one by one.
They look at the name tag and go straight to that slot.
In an array, not knowing the spot means searching from box 1,
but with a key you arrive in one jump. That's the speed secret.
Left searches one by one; right jumps straight there by name tag. Tap to compare.
Knowing the name means no long detour.
That's why key and value are so strong at
'pulling one thing out fast from many'.
Finally, there's one rule the name tags must keep.
Name tags don't repeat
There's just one rule.
The same name tag can be used only once.
You can add as many new tags as you like,
but if you put a new value under a tag that already exists,
the old value is erased and replaced with the new one.
A new tag adds a slot; reusing a tag swaps the old value for the new one.
Because tags never repeat,
calling 'Minsu' is never ambiguous.
Exactly one value always comes back.
This one simple pair is actually hiding everywhere.
Pairs everywhere, and beyond
Dictionaries (word->meaning), settings (option->value),
contacts (name->number), a game bag (item->count).
All key and value.
It's one of the most common ways to organize data.
Next, we'll bundle these name tags into one chunk
and treat them as 'a single thing'.
Dictionary, settings, contacts, bag. Tap through them. All the same 'key -> value'.
After arrays in a row (lesson 8),
you now also hold key and value, found by name.
You can handle data by number and by name.
Next, we'll put several name tags into one box
and bundle them as 'one thing': objects.