Lesson 27. Dictionaries as maps between objects

 

After reading lesson 27, you’ll be able to

  • Understand what a dictionary object data type is
  • Add to, remove from, and look up objects in dictionaries
  • Understand when to use a dictionary object
  • Understand the difference between a dictionary and a list

In the previous lesson, you learned about lists as collections of data with elements at a certain position in the list. Lists are useful when you want to store one group of objects; you saw that you could store a group of names or a group of numbers. But in real life, you often have pairs of data: a word and its meaning, a word and a list of synonyms, a person and their phone number, a movie and its rating, a song and its artist, and many others.

Figure 27.1 takes the grocery list metaphor from the previous lesson and shows you one way to apply it to dictionaries. In a list, your grocery items are enumerated; the first item is on the first line, and so on. You can think of a list as mapping the numbers 0, 1, 2, and so on, in that order, to each item in your list. With a dictionary, you get additional flexibility in what you can map, and to what. In figure 27.1, the grocery dictionary now maps an item to its quantity.

Figure 27.1. A list puts the first item at position 0, the second item at position 1, and the third at position 2. A dictionary doesn’t have positions, but rather maps one object to another; here it maps a grocery item to its quantity.

27.1. Creating dictionaries, keys, and values

 
 
 

27.2. Adding key-value pairs to a dictionary

 
 

27.3. Removing key-value pairs from a dictionary

 

27.4. Getting all the keys and values in a dictionary

 
 

27.5. Why should you use a dictionary?

 
 
 

Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage