Dictionary

Example of a dictionary

The dictionary, also called a map or hashmap, is one of the most commonly used data structures. It stores key-value pairs.

Creating dictionaries

O(1)

You can use curly brackets to create a dictionary, or dict(). Just stick to one for consistency.

We can initialize dictionaries with values. This is useful when we're creating constant dictionaries or asked to create test cases.

Example of initializing a dictionary

Sometimes, you'll want to initialize a dictionary and add key-value pairs to it flexibly.

  • defaultdict(list) creates an empty dictionary, and every new pair is initialized with a list as its value
  • defaultdict(int) creates an empty dictionary, and every new pair is initialized with 0 as its value
Diagram of dictionary in Python
1 of 2

Adding to dictionaries

O(1)

We recommend using subscript notation (square brackets) to add elements to an existing dictionary.

Example of initializing types dictionary

Removing an item from a dictionary

O(1)

To remove an item from a dictionary, you can use pop()or del . The main differences are:

  1. pop() removes the key and returns a value that was at that key. It raises an error if the key is missing unless a fallback value is given.
  2. del removes the key without returning a value. It raises an error if the key is missing. It's also slightly faster.

We recommend using pop() because it's more versatile and easier to remember. Interviewers likely will be focused on algorithm complexity, not nuances of speed between different methods anyway.

Example of removing from a dictionary

Getting values from dictionaries

O(1)

You can use subscript notation to get an item from the dictionary. However, an exception will be thrown if the key doesn't exist.

Alternatively, you can use the .get() method. You can optionally provide a default value as a second parameter if the key doesn't exist.

Example of a lookup in a dictionary