A dictionary stores data as key: value pairs, so you can look a value up by name instead of by position. A phone book, a student's record, the settings of an app and almost every JSON response from a web API are dictionaries.
This tutorial covers creating and reading dictionaries, safe lookups with get, updating and deleting, looping, nested dictionaries, dictionary comprehensions and counting.
Creating a dictionary
Use curly braces, with a colon between each key and its value:
student = {"name": "Ahana", "course": "BTech", "year": 2}
empty = {}
Keys are usually strings, but any immutable value works: numbers and tuples too. Values can be anything, including lists and other dictionaries. Each key appears only once; assigning to an existing key replaces its value.
Reading values
student["name"] # 'Ahana'
student["email"] # KeyError: 'email'
Reading a key that doesn't exist raises a KeyError. When a key might be missing, use get, which returns None, or a default you choose:
student.get("email") # None
student.get("email", "not given") # 'not given'
"email" in student # False: check for a key
Adding, changing and deleting
student["email"] = "ahana@example.com" # add a new key
student["year"] = 3 # change an existing one
student.update({"year": 3, "city": "Kanpur"}) # several at once
del student["city"] # delete a key
email = student.pop("email") # delete and return the value
Like remove on lists, del raises a KeyError if the key is missing. student.pop("email", None) doesn't.
Looping over a dictionary
Looping over a dictionary gives its keys. Use .items() to get keys and values together:
prices = {"tea": 15, "samosa": 20, "coffee": 30}
for item in prices: # keys
print(item)
for item, price in prices.items(): # keys and values
print(f"{item}: ₹{price}")
total = sum(prices.values()) # 65
Since Python 3.7, dictionaries keep the order in which keys were added.
Counting with a dictionary
Counting things is one of the most common uses of a dictionary:
words = "the cat and the dog and the bird".split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts) # {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
counts.get(w, 0) returns 0 the first time a word appears, so there is no KeyError. The standard library's collections.Counter does the same in one line: Counter(words).
Nested dictionaries
Values can be dictionaries or lists, which is how JSON data looks:
students = {
"S01": {"name": "Ahana", "marks": [88, 92]},
"S02": {"name": "Rohan", "marks": [72, 65]},
}
students["S02"]["name"] # 'Rohan'
students["S01"]["marks"][1] # 92
for sid, info in students.items():
average = sum(info["marks"]) / len(info["marks"])
print(sid, info["name"], average) # S01 Ahana 90.0, then S02 Rohan 68.5
Dictionary comprehensions
Like a list comprehension, but it builds a dictionary:
squares = {n: n * n for n in range(1, 5)} # {1: 1, 2: 4, 3: 9, 4: 16}
prices = {"tea": 15, "samosa": 20, "coffee": 30}
cheap = {k: v for k, v in prices.items() if v < 25} # {'tea': 15, 'samosa': 20}
Why dictionaries are fast
A dictionary finds a key using a hash of it, so a lookup takes about the same time whether it holds ten keys or ten million: O(1) on average. Searching a list with in checks every item, which is O(n). If you keep searching a big list for things, a dictionary or a set is usually the fix. Big-O notation explains why.
When your data becomes a table of many records, such as many students with the same fields, a pandas DataFrame is the next step. You can even create one from a list of dictionaries.
Practice
- Given
stock = {"pens": 40, "books": 12}, add 10 pencils, then increase the books by 5.
Show the answer
stock["pencils"] = 10
stock["books"] += 5
print(stock) # {'pens': 40, 'books': 17, 'pencils': 10}
- Count how many times each letter appears in
"banana".
Show the answer
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}
- From
marks = {"Ahana": 88, "Rohan": 72, "Meera": 95}, find the name with the highest mark.
Show the answer
max(marks, key=marks.get) # 'Meera'
max loops over the keys and compares them by marks.get(key), their marks.
- Swap keys and values: turn
{"a": 1, "b": 2}into{1: "a", 2: "b"}.
Show the answer
d = {"a": 1, "b": 2}
{v: k for k, v in d.items()} # {1: 'a', 2: 'b'}
If two keys share a value, only the last one survives, because keys must be unique.
Interview questions
What can be a dictionary key?
Any hashable value: strings, numbers, booleans, and tuples that contain only hashable values. Lists, dictionaries and sets can't be keys, because they are mutable.
What is the difference between d[key] and d.get(key)?
d[key] raises a KeyError if the key is missing. d.get(key) returns None, or the default you pass as its second argument.
What is the time complexity of a dictionary lookup?
O(1) on average, because dictionaries are hash tables. In the rare worst case, with many hash collisions, it can degrade to O(n).
Are Python dictionaries ordered?
Yes. Since Python 3.7, dictionaries are guaranteed to keep the order in which keys were inserted.
What to learn next
- Organise your dictionary code into Python functions.
- Save dictionaries to disk as JSON with Python file handling.