Dictionary

Example of a dictionary

A dictionary stores key-value pairs. You might also hear it called a map or a hashmap. It’s one of the data structures you’ll use most in interviews.

Creating dictionaries

O(1)

You can use curly brackets to create a dictionary, or dict(). Pick one and use it every time. That keeps your code consistent.

grocery_prices = {}
print(grocery_prices)
grocery_prices = dict()
print(grocery_prices)
main.py

You can also start a dictionary with values already in it. This is handy when you need a dictionary that never changes. It’s also handy when you’re writing test cases.

Example of initializing a dictionary
grocery_prices = {"eggs": 8.34, "broccoli": 2.99}
print(grocery_prices)
main.py

Sometimes you want every new key to start with a default value. That’s what defaultdict is for.

  • defaultdict(list) creates an empty dictionary. Each time you use a new key, its value starts as an empty list.
  • defaultdict(int) creates an empty dictionary. Each time you use a new key, its value starts at 0.
Diagram of dictionary in Python 1: a defaultdict(list) where "mouse" and then "keyboard" are appended to the list under the "electronics" key
Diagram of dictionary in Python 2: a defaultdict(int) where the "New York" key starts at 0, then drops by 5 and then by 2
1 / 2

Use ← → arrow keys

map = defaultdict(list)
print(map)
map["electronics"].append("mouse")
map["electronics"].append("keyboard")
print(map)

celsius = defaultdict(int)
print(celsius)
celsius["New York"] -= 5
print(celsius)
celsius["New York"] -= 2
print(celsius)
main.py

Adding to dictionaries

O(1)

To add an item to a dictionary, we recommend using square brackets.

Example of adding a key to a dictionary
grocery_prices = {"eggs": 8.34, "broccoli": 2.99}
grocery_prices["tofu"] = 3.29
print(grocery_prices["tofu"])
main.py

Removing an item from a dictionary

O(1)

To remove an item from a dictionary, you can use pop()or del . Here’s how they’re different:

  1. pop() removes the key and returns the value that was stored there. It raises an error if the key is missing, unless you pass in a fallback value.
  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 does more and it’s easier to remember. Interviewers care about your algorithm’s time complexity. They won’t care about small speed differences between two methods.

Example of removing from a dictionary
grocery_prices = {"eggs": 8.34, "broccoli": 2.99, "tofu": 3.29}
print(grocery_prices.pop("eggs"))
del grocery_prices["broccoli"]
print(grocery_prices)
main.py

Getting values from dictionaries

O(1)

You can use square brackets to get an item from the dictionary. However, Python throws an exception if the key doesn’t exist.

You can also use the .get() method. It lets you pass a default value as the second argument. You get that value back if the key doesn’t exist.

Example of a lookup in a dictionary
grocery_prices = {"eggs": 8.34, "broccoli": 2.99, "tofu": 3.29}
print(grocery_prices["tofu"])
print(grocery_prices.get("tofu", 1.99))
grocery_prices.pop("tofu")
print(grocery_prices.get("tofu", 1.99))
main.py

Getting keys, values, or key-value pairs

O(1)
You can also pull out just the keys, just the values, or both:
  • keys() gets the keys
  • values() gets the values
  • items() gets the (key, value) pairs together
Example of getting keys(), values(), and items() from a dictionary
unicode = {'a': 97, 'b': 98, 'c': 99}
print(unicode.keys())
print(unicode.values())
print(unicode.items())
for character, decimal in unicode.items():
  print(f'The Unicode decimal value of {character} is {decimal}.')
main.py