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.
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)We recommend using subscript notation (square brackets) to add elements to an existing 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:
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.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.
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.
Thank you!