Python Dictionaries
A dictionary stores data as key-value pairs, so you can look a value up by a meaningful key instead of a position. Dictionaries model JSON, configuration, database rows and counters, which makes them one of the most used types in Python.
- Create dictionaries and read values safely
- Add, update and delete keys
- Loop over keys, values and items
- Work with nested dicts and merging
Create a dictionary
Write key: value pairs inside curly braces. Keys are usually strings, but any immutable value works.
user = {"name": "Asha", "role": "tester", "years": 4}print(user)print(len(user)) ports = dict(http=80, https=443) # dict() with keyword argumentsprint(ports){'name': 'Asha', 'role': 'tester', 'years': 4}
3
{'http': 80, 'https': 443}Since Python 3.7, dictionaries keep the order in which keys were inserted.
Read values
Use square brackets with the key. A missing key raises KeyError, so use get() when a key may be absent.
user = {"name": "Asha", "role": "tester"}print(user["name"])print(user.get("email")) # None instead of an errorprint(user.get("email", "not provided")) # with a defaultprint("role" in user) # checks keysAsha None not provided True
user = {"name": "Asha"}print(user["email"])Traceback (most recent call last):
File "main.py", line 2, in <module>
print(user["email"])
~~~~^^^^^^^^^
KeyError: 'email'Add, change and delete
config = {"browser": "chromium", "headless": True} config["timeout"] = 30 # add a new keyconfig["browser"] = "firefox" # replace an existing valueconfig.update({"retries": 2, "headless": False})print(config) removed = config.pop("retries") # remove and returndel config["timeout"] # removeprint(removed, config){'browser': 'firefox', 'headless': False, 'timeout': 30, 'retries': 2}
2 {'browser': 'firefox', 'headless': False}setdefault() returns a key’s value, adding it with a default first if it is missing:
groups = {}for name, team in [("asha", "qa"), ("ravi", "dev"), ("meena", "qa")]: groups.setdefault(team, []).append(name)print(groups){'qa': ['asha', 'meena'], 'dev': ['ravi']}Loop over a dictionary
stock = {"pen": 40, "notebook": 0, "bag": 7} for item in stock: # keys print(item, end=" ")print() print(list(stock.values())) for item, qty in stock.items(): # key and value together if qty == 0: print(item, "is out of stock")pen notebook bag [40, 0, 7] notebook is out of stock
Count things with a dict
Counting is the classic dictionary job:
text = "the quick brown fox jumps over the lazy dog the end"counts = {}for word in text.split(): counts[word] = counts.get(word, 0) + 1 print(counts["the"])top = max(counts, key=counts.get)print(top, counts[top])3 the 3
collections.Counter does this in one line: Counter(text.split()).most_common(1). See the Collections lesson.
Nested dictionaries
Values can be lists or other dictionaries, which is exactly the shape of JSON data.
response = { "status": 200, "data": { "user": {"id": 7, "name": "Ravi"}, "roles": ["admin", "tester"], },}print(response["data"]["user"]["name"])print(response["data"]["roles"][-1])print(response.get("error", {}).get("message", "no error"))Ravi tester no error
Merge dictionaries
defaults = {"browser": "chromium", "headless": True, "timeout": 30}overrides = {"headless": False} settings = defaults | overrides # Python 3.9+print(settings)print({**defaults, **overrides} == settings){'browser': 'chromium', 'headless': False, 'timeout': 30}
TrueWhen both have the same key, the value from the right-hand dict wins.
Dictionary methods
| Method | What it does |
|---|---|
get(k, default) | Value for k, or default if missing |
keys(), values(), items() | Views of the keys, values or pairs |
update(other) | Adds or replaces keys from another dict |
pop(k) | Removes k and returns its value |
popitem() | Removes and returns the last inserted pair |
setdefault(k, d) | Returns k‘s value, inserting d first if missing |
copy() | Shallow copy |
clear() | Removes everything |
dict.fromkeys(keys, v) | New dict with each key set to v |
Sort a dictionary
scores = {"Asha": 88, "Ravi": 74, "Meena": 93}print(sorted(scores)) # keysprint(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))ranked = dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))print(ranked)['Asha', 'Meena', 'Ravi']
[('Meena', 93), ('Asha', 88), ('Ravi', 74)]
{'Meena': 93, 'Asha': 88, 'Ravi': 74}Check your understanding
Predict the output
d = {"a": 1, "b": 2}d["a"] += 10d.setdefault("c", 3)d.setdefault("a", 99)print(d, d.get("z", 0)){'a': 11, 'b': 2, 'c': 3} 0setdefault adds "c" because it is missing, but leaves "a" alone because it already exists.
Quick quiz
1. What does d.get("x") return when “x” is not a key?
get() returns None, or the default you pass as the second argument.
2. Which loop gives both keys and values?
items() yields (key, value) pairs.
3. Which of these can NOT be a dictionary key?
Keys must be hashable; lists are mutable.
4. In a | b, if both dicts have key “x”, whose value is kept?
The right-hand operand wins.
Exercise: invert a dictionary
Swap keys and values of a country-code dict, then look up the code for “India”.
{"IN": "India", "US": "United States", "JP": "Japan"}{'India': 'IN', 'United States': 'US', 'Japan': 'JP'}
INHint 1
A dict comprehension: {v: k for k, v in codes.items()}.
codes = {"IN": "India", "US": "United States", "JP": "Japan"}by_name = {name: code for code, name in codes.items()}print(by_name)print(by_name["India"]){'India': 'IN', 'United States': 'US', 'Japan': 'JP'}
INThe comprehension walks over each (code, name) pair and builds a new dict with the name as the key. This only works safely when the values are unique.
Program Practice
94 Python Dictionary Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python dictionary FAQ
Are Python dictionaries ordered?
Yes. Since Python 3.7, dictionaries preserve insertion order.
How do I check if a key exists in a dictionary?
Use in: if "email" in user:. Use get() when you also want the value.
How do I merge two dictionaries in Python?
Use a | b (Python 3.9+) or {a, b} to create a new dict, or a.update(b) to change a in place.
What is the difference between dict.get() and dict[key]?
dict[key] raises KeyError if the key is missing. dict.get(key) returns None or a default instead.