Instructor: Welcome back.
I mentioned to you that a dictionary's values
can hold any sort of data type.
But what about the keys?
Up until now, I've only used strings to denote a key.
But could I do something like this?
Could I do 123 like this?
Well, let's have a look.
Let's give it a try.
If I do 123,
and I click run,
I get 1, 2, 3.
Awesome, that works.
What about True?
If I have a key True and I click run, will that work?
Yep, It looks like it works.
What about a list?
What if I have a list of let's say just 100?
Would that work?
If I click run, nope, it doesn't work.
It says unhashable type list.
What does that mean?
Dictionary keys need to have a special property.
A key needs to be immutable.
That is a key cannot change.
And numbers, Booleans,
I mean, this is a value that cannot change.
A string, if you remember, is a value that cannot change.
It's immutable.
But a list, if you remember, can be changed, right?
On a list, I can reassign,
let's say the index of zero to something else, right?
So because of that, a dictionary says,
"Hey, my keys,
because I'm storing them in memory,
and I don't wanna lose them,
it has to be something that isn't going to change on me."
Maybe a programmer comes in
and by mistake changes this array of 100
to have an index of something else.
Well, dictionary doesn't really want that
because it doesn't wanna lose this value.
So a dictionary key always has to be immutable.
And as we learn a few other things,
like a tuple that we'll see in upcoming videos,
you can use those as keys as well.
However, most of the time, 95/99% of the time,
a key for a dictionary is usually something descriptive,
like a string.
Okay, but what about this?
What if we have another string?
123, and let's just remove this for now.
What happens when I search for 123, this string?
If I click run, I get hello.
A key in a dictionary has to be unique,
because there can only be one key,
because that key is gonna represent
a bookshelf in that memory space.
So anytime I do the same key,
and maybe add a value, it's going to override.
So this no longer exists.
A key has to be unique,
and it's something that can only exist, well, just once.
Otherwise, we override it, which is why you see hello here.
We've lost the array 1, 2, 3.
Let's explore this idea a little bit more in the next video.