Dictionaries

Let's learn about dictionary objects, nesting dictionaries, and different methods of dictionary objects.

Concept

A dictionary A dictionary is an object that stores a collection of data. Each element in a dictionary has two parts: a key and a value. We use keys to locate specific values.

For many of us, the word “dictionary” elicits an image of a large book—such as the Merriam-Webster dictionary—that contains words and their definitions. If we want to know the meaning of a particular word, we locate it in the dictionary to find its definition.

In Python, a dictionary is an object that stores data collection in the form of key-value pairs. When we want to retrieve a specific value from a dictionary, we use the key associated with that value. This is similar to the process of looking up a word in the Merriam-Webster dictionary, where, by analogy, the words are keys and the definitions are values.

For example, let’s suppose there’s a company in which each employee has an ID number. We want to write a program that lets us look up any employee’s name by entering their ID number. To accomplish this, we can create a dictionary in which each element contains an employee’s ID number as the key and the employee’s name as the value. Thus, using this program, if we know an employee’s ID number, then we can easily retrieve their name.

Another example of a program that uses a dictionary would be one that lets us enter a person’s name to get that person’s phone number. The program could use a dictionary in which each element contains a person’s name as the key and that person’s phone number as the value. If we know a person’s name, then we can retrieve that person’s phone number.

Key-value pairs are often referred to as mappings because each key is mapped to a value.

  • Dictionaries are key-value pairs in curly brackets {}.
  • Dictionaries store objects by key instead of relative position and don’t maintain any reliable left-to-right order. They map keys to the associated values.
  • We can expand and shrink dictionaries like lists.

Get hands-on with 1200+ tech skills courses.