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)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.
grocery_prices = {"eggs": 8.34, "broccoli": 2.99}
print(grocery_prices)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.
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)Adding to dictionaries
O(1)To add an item to a dictionary, we recommend using square brackets.
grocery_prices = {"eggs": 8.34, "broccoli": 2.99}
grocery_prices["tofu"] = 3.29
print(grocery_prices["tofu"])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:
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.delremoves 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.
grocery_prices = {"eggs": 8.34, "broccoli": 2.99, "tofu": 3.29}
print(grocery_prices.pop("eggs"))
del grocery_prices["broccoli"]
print(grocery_prices)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.
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))Getting keys, values, or key-value pairs
O(1)keys()gets the keysvalues()gets the valuesitems()gets the (key, value) pairs together
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}.')