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.
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
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:
pop()
will return the value (or the default value if provided) whiledel
does not. They will both throw errors if the key does not exist (unless pop is given a default value).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.