Previous Lesson: Lesson 15: Range in Python
How do dictionaries work in Python? Is it really that similar with lists? But it should have something that lists don’t have, eh? Find out in this lesson!
Let’s type this on a new file: ex13.py:
Each element (that’s separated with the comma) in a dictionary is represented by a key:value pair. Dictionaries can be indexed in the same way as lists using square brackets () containing the key. On our dictionary, our keys are ‘smile’, ‘job’, and ‘hi’. Their own values are the ones after each colon (:). So if there are three keys, there are three values.
Let’s see what happens if we print out the value of the key ‘smile’:
Great! If we’ll get back to our code and locate the ‘smile’ in our dictionary, its value (which is ‘happy’) got printed out! “So it works like an actual dictionary? Like the Merriam Webster’s Dictionary?” Yes, it’s mainly like that.
ints as Keys in a Dictionary
We can also use ints as keys to our dictionary:
Note: It is important to remember that we can only use the keys for indexing.
Line 6 should print out ‘Zedd’; Line 7 should print out ‘Maru’; and then Line 8 should print out, not ‘Icy’ (because it’s a key), but the int 3. Let’s see if these check out:
To make our code more understandable and more readable, we can actually do this. And that’s only if you are really comfortable with this. But let me tell you that once you’ve got a lot inside your dictionary, this is how one would do it:
It should have the same results:
Lists inside a Dictionary
What? Why make everything so complicated? You’ll understand as we continue with the lesson. Just take note that these lists are the values of the colors. With all that being said, let’s type this:
Anyway, in case you’re wondering what these numbers are, I’m gonna tell you that I did not just invent these numbers. Rather, these are called hexadecimal colors (and that’s what that HEX means). Which means real people (even programmers) use these numbers. But you don’t have to worry about that now. But in case you’re interested, you can check out that link reference. Okay, now let’s run this:
Great! This is another example. Hopefully, you understand the importance of this to our daily lives. Let’s say that I want to know the kind of pencils I want to buy when I’m at the store. So what I’ll do is print(drawing[“pencils”]) to get my lists on that key:
“What are the kind of pencils that I’ve listed? Mmm. . . let’s see”:
It’s that simple! This is another example. This time, it is a dictionary of family members:
Let’s see the members on the Fabian family:
Nice! Now that I have their names, all I need to do now is to invite them all in my graduation party. All of these were fun right? However, we can’t use lists as our key; they can only be used as the values. You’ll see why in our next lesson.