Video Pending

Created by Zed A. Shaw Updated 2024-02-17 04:54:36
 

24: Introductory Dictionaries

In this exercise we'll use the same data from the previous exercise on lists and use it to learn about Dictionaries or dicts.

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:

  1. Opening it with a { (curly-brace).
  2. Writing the key, which is a string here, but can be numbers, or almost anything.
  3. Writing a : (colon).
  4. 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).

Previous Lesson Next Lesson

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.