Dictionary

The dictionary, also referred to as the map or hashmap, is one of the most commonly used data structures in Python. It serves as a container for storing key-value pairs. Let's explore some simple examples and learn a few handy techniques when working with dictionaries.

Creating dictionaries

Although there are many ways to create a dictionary, for interviews, it's best to consistently stick to one approach. The simplest way is to use curly brackets (alternatively, you can use dict(), but just stick to one for consistency).

Initializing dictionaries with predefined values is also important. Instead of adding the key-value pairs one by one, we can initialize them within the dictionary constructor. This is useful when we are creating constant dictionaries or asked to create test cases.

Adding to dictionaries

O(1)

There are several ways to add elements to an existing dictionary, each with slightly different behaviors. I recommend using subscript notation (square brackets).

Removing an item from a dictionary

O(1)

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

  1. pop() will return the value (or the default value if provided) while del does not. They will both throw errors if the key does not exist (unless pop is given a default value).
  2. del is slightly faster.

I recommend using pop() in all cases, even if you don't need the default value, 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.

Getting values from dictionaries

O(1)

There are two ways I recommend that you get items from a dictionary. The first is through subscript notation which is your standard approach. The second is to use the get ("()") method, particularly when you aren't sure if the key exists and you need to provide default values.