Video Coming Soon...
24: Introductory Dictionaries
In this exercise we'll use the same data from the previous exercise on list
s and use it to learn about Dictionaries
or dict
s.
Key/Value Structures
You use key=value
data all the time without realizing it. When you read an email you might have:
From: j.smith@example.com
To: zed.shaw@example.com
Subject: I HAVE AN AMAZING INVESTMENT FOR YOU!!!
On the left are the keys (From, To, Subject) which are mapped to the contents on the right of the :
. Programmers say the key is "mapped" to the value, but they could also say "set to". As in, "I set From
to j.smith@example.com
." In Python I might write this same email using a data object like this:
email = {
"From": "j.smith@example.com",
"To": "zed.shaw@example.com",
"Subject": "I HAVE AN AMAZING INVESTMENT FOR YOU!!!"
};
You create a data object by:
- Opening it with a
{
(curly-brace). - Writing the key, which is a string here, but can be numbers, or almost anything.
- Writing a
:
(colon). - Writing the value, which can be anything that's valid in Python.
Once you do that, you can access this Python email like this:
email["From"]
'j.smith@example.com'
email["To"]
'zed.shaw@example.com'
email["Subject"]
'I HAVE AN AMAZING INVESTMENT FOR YOU!!!'
The only difference from list
indexes is that you use a string ('From'
) instead of an integer. However, you could use an integer as a key if you want (more on that soon).
Register for Learn Python the Hard Way, 5th Edition (2023-2024)
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.