Dictionaries


Learning Objectives

After this lesson, you will be able to:

  1. Differentiate between a key and a value.
  2. Differentiate between a dictionary and a list.
  3. Use dictionaries to solve common problems in Python.

Introducing Dictionaries

Before learning about loops, we learned about lists:

  • Store data items in a single place.
  • Access them using a zero-based index.
  • We can use them in other parts of our script or modify them to contain new values.

Introducing Dictionaries

Python also provides us with a type of list called a dictionary.

  • Works much like an actual dictionary. To find the definition associated with a given word:
    • Go to the dictionary.
    • Turn straight to the word you are interested in.
    • Don’t have to iterate through every definition.
    • Don’t have to know its exact index number.

Introducing Dictionaries

  • Use meaningful keys.
  • A direct reference to that element in the dictionary.
  • We call that a key-value pair: The key is used to find the associated value.
  • A key can be any string or integer we like, in whatever order we like.

Introducing Dictionaries


Introducing Dictionaries


Introducing Dictionaries

  • In a dictionary, all keys must be unique.
  • Especially useful when you have a small-but-meaningful “key” data point that can be used as an index for an associated value in the collection.
  • Example: A collection of cars with each car linked to the first name of its owner.

Let’s get some practice:


Code-Along: Dictionary Syntax

Use the curly braces to denote the start and end of the collection

Here, our dictionary is called friendzips, 98107 is a key, and "Lauren" is the value that goes with that key.


Code-Along: Dictionary Syntax

Now, we can use the keys (zip codes, in this example) to find the values, i.e., the friend we have in that zip code:

We’re asking Python to look at the dictionary friendzips and print the value for the key 92211. This will print "Markus".


Code-Along: Dictionary Syntax

If Markus moves away and we want to change the value associated with 92211 with the new person that moves in, then we can easily do so in a similar fashion to how it’s done with a list:

When we run this, we see that the value at the 92211 is replaced with 'Jackie'. It’s as simple as that to get or set values in a dictionary!


Code-Along: Dictionary Syntax

Note: The order of names you see printed may differ from how you entered them. It’s important to know that dictionaries have no inherent order!

  • The items that are returned when you access a dictionary come in any order they please.
  • This doesn’t really matter that much, however, because the typical use case for a dictionary is when you know the exact key for the value you’re looking for.
  • But, you should never count on the contents of a dictionary being in any order at all.

Code-Along: Dictionary Syntax

What happens if you try to print a key that isn’t defined? Try running the code:

You’ll get an error.


String Keys

It is also common to use strings for keys.

If you print bookAuthors, it should work.


String Keys

Now, let’s try making a dictionary that has lists for the values:

  • State abbreviations as keys.
  • Each one points to a list of names.
  • We can even use dictionaries as values!

String Keys

  • Each item is on one line ending with a comma.
  • We still have our key-value pair format separated by commas, however, making it easily readable to a human, which is a good thing.

  • We can do this with any dictionary, regardless of its contents.
  • The syntax will remain the same.

Change your dictionary to look like this:

```python
friendzips = {
  98107: "Lauren",
  92211: "Markus",
  90210: "Brenda"
}
```

String Keys

  • Same dictionary
  • Line-by-line formatting makes it easier for a person to read,
  • Saves time during maintenance.
  • This is a best practice.

Looping Through Dictionaries

Now, how do we loop through a dictionary? We can use the same for loop structure, but, instead of it iterating over each element in the collection, it will iterate over each key. We can then use the key to access the value:


Looping Through Dictionaries

The lines in our for loop work like this:

  • The first line says, “For every key in the friendzips dictionary…”
  • The second line says, “… print the value in friendzips associated with the provided key.”

You-Do: Collection Identification Practice

Identify the type of each collection:

```python
# a.
coll1 = [3, 5, 7, "nine"]
# b.
coll2 = {"SM": 8, "MD": 12, "LG": 16}
```

You-Do: Collection Practice

Use this blank repl.it workspace for this practice.

  1. Write a script that declares a dictionary named letters. Add a key to this dictionary for each unique letter in your full name (first and last). The value for these keys should be how many times that letter appears in your name. As an example, here are the dictionaries you’d make for the names “Joe” and “Callee:”

  2. Using the dictionary you just created, write a loop below it that prints a nice message telling us the number of occurrences of a letter in your name. Something like:

  3. Create a dictionary that uses strings as the keys and dictionaries as values. Loop through the dictionaries to output all the values.


Conclusion

Here are the key takeaways from this lesson:

  • A dictionary is another kind of collection, similar to a list, except that it uses keys to access elements instead of indices.
  • Dictionaries should be used instead of lists when you don’t care about the order of the items and when you’d prefer more meaningful keys than integers for accessing the collection’s values.

To deepen your understanding, consider exploring some of the resources in the Additional Reading section that follows.


Additional Reading