Python Dictionaries
A dictionary is Python's built-in key-value store — the backbone of JSON parsing, configuration management, database row mapping, and almost every non-trivial Python program. Dictionaries give you O(1) lookup by any key, maintain insertion order (Python 3.7+), and support any hashable type as a key. This chapter covers creating dicts with a visual diagram, accessing and updating values, all dict methods, iterating, nested dicts, and powerful dict comprehensions.
Creating Dictionaries
A dictionary stores data as key-value pairs inside curly
braces {}. Each key is separated from its value by a colon,
and pairs are comma-separated. Keys must be unique and hashable (strings,
numbers, tuples). Values can be anything. As of Python 3.7+, dicts maintain
insertion order.
# Curly brace syntax
person = {
"name": "Alice",
"age": 25,
"city": "Vadodara",
"active": True
}
# dict() constructor
config = dict(host="localhost", port=8080, debug=False)
# Empty dictionary
empty = {}
empty2= dict()
# From list of (key, value) pairs
pairs = dict([("a", 1), ("b", 2), ("c", 3)])
print(pairs) # {'a': 1, 'b': 2, 'c': 3}
# From two lists using zip
keys = ["name", "age", "city"]
values = ["Bob", 30, "Mumbai"]
user = dict(zip(keys, values))
print(user) # {'name': 'Bob', 'age': 30, 'city': 'Mumbai'}
# Dict properties
print(len(person)) # 4
print(type(person)) # <class 'dict'>
print("name" in person) # True — key membership test
print("email" in person) # False
Accessing Values — [] vs get()
You can access values in two ways: square bracket notation
d[key] raises a
KeyError if the key is absent, while
d.get(key) returns
None (or a default you provide) — never raising an error.
Always prefer get() when you're not sure a key exists.
person = {"name": "Alice", "age": 25, "city": "Vadodara"}
# [] notation — raises KeyError if key absent
print(person["name"]) # Alice
print(person["age"]) # 25
# person["email"] → KeyError: 'email'
# get(key) — returns None if key absent (safe!)
print(person.get("name")) # Alice
print(person.get("email")) # None — no error!
# get(key, default) — custom default value
print(person.get("email", "not set")) # not set
print(person.get("age", 0)) # 25 (key exists)
# Accessing nested values
data = {"user": {"name": "Bob", "score": 98}}
print(data["user"]["name"]) # Bob
# Check key existence before accessing
if "age" in person:
print(f"Age: {person['age']}") # Age: 25
KeyError otherwise.
None) when the
key is missing. The Pythonic choice for uncertain keys.
Adding, Updating & Removing Entries
Dictionaries are mutable — you can add new key-value pairs, change existing values, and delete entries. Assignment to a new key adds it; assignment to an existing key updates it.
person = {"name": "Alice", "age": 25}
# Add new key-value pair
person["city"] = "Vadodara"
print(person) # {'name': 'Alice', 'age': 25, 'city': 'Vadodara'}
# Update existing value
person["age"] = 26
print(person["age"]) # 26
# update() — merge another dict or key-value pairs
person.update({"email": "alice@example.com", "age": 27})
print(person)
# adds email, updates age to 27
# update() with keyword arguments
person.update(role="developer", active=True)
# Merge with | operator (Python 3.9+)
extra = {"team": "backend"}
merged = person | extra # new dict
person |= extra # in-place merge
# del — remove a key (KeyError if absent)
del person["team"]
# pop(key) — remove and RETURN value
email = person.pop("email")
print(email) # alice@example.com
missing = person.pop("phone", "not set") # safe pop
print(missing) # not set
# popitem() — remove and return last (key, value) pair
last = person.popitem()
print(last) # last inserted item
# clear() — remove everything
temp = {"a": 1}
temp.clear()
print(temp) # {}
Iterating Dictionaries
Python provides three views for iterating dicts: keys() for
keys only, values() for values only, and
items() for key-value pairs. The most Pythonic approach is
for k, v in d.items(). All three return
view objects — they reflect real-time changes to the dict.
scores = {"Alice": 90, "Bob": 85, "Carol": 92}
# Iterate keys (default)
for name in scores:
print(name, end=" ") # Alice Bob Carol
# Iterate keys explicitly
for name in scores.keys():
print(name, end=" ") # Alice Bob Carol
# Iterate values
for score in scores.values():
print(score, end=" ") # 90 85 92
# Iterate key-value pairs — most Pythonic!
for name, score in scores.items():
print(f"{name}: {score}")
# Alice: 90 Bob: 85 Carol: 92
# Check membership (keys only by default)
print("Alice" in scores) # True
print(90 in scores.values()) # True
# Convert views to list
print(list(scores.keys())) # ['Alice', 'Bob', 'Carol']
print(list(scores.values())) # [90, 85, 92]
# Sorted iteration
for name in sorted(scores):
print(f"{name}: {scores[name]}")
# Sum of values, find max
print(sum(scores.values())) # 267
print(max(scores, key=scores.get)) # Carol (highest score)
All Dict Methods
Python dictionaries come with a rich set of built-in methods. The most important is
setdefault() — it retrieves a value if the key exists, or
inserts a default and returns it if the key is missing. This avoids the common "check-then-set"
pattern.
d = {"a": 1, "b": 2, "c": 3}
# setdefault(key, default) — get if exists, insert if not
print(d.setdefault("a", 99)) # 1 — "a" exists, return its value
print(d.setdefault("d", 99)) # 99 — "d" absent, insert and return
print(d) # {'a':1,'b':2,'c':3,'d':99}
# copy() — shallow copy
d2 = d.copy()
d2["a"] = 999
print(d["a"]) # 1 — original unchanged
# fromkeys(iterable, value) — class method, create new dict
template = dict.fromkeys(["x","y","z"], 0)
print(template) # {'x': 0, 'y': 0, 'z': 0}
# Practical: group items with setdefault
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for w in words:
groups.setdefault(w[0], []).append(w)
print(groups)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
# Counting with get() + default
sentence = "the cat sat on the mat"
freq = {}
for word in sentence.split():
freq[word] = freq.get(word, 0) + 1
print(freq)
# {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
| Method | Description | Returns |
|---|---|---|
get(k, d) |
Return value for k, or d if absent | value / default |
pop(k, d) |
Remove k and return value; d if absent | value / default |
popitem() |
Remove and return last (k, v) pair | (key, value) |
setdefault(k, d) |
Return value if k exists; insert d and return it if not | value |
update(other) |
Add/overwrite keys from dict/iterable | None |
keys() |
View of all keys | dict_keys |
values() |
View of all values | dict_values |
items() |
View of all (key, value) pairs | dict_items |
copy() |
Shallow copy of the dict | dict |
clear() |
Remove all items | None |
fromkeys(iter, v) |
New dict with keys from iter, all set to v | dict |
Nested Dictionaries
Nested dicts — dictionaries that contain other dictionaries as values — are how Python models hierarchical and structured data. They mirror JSON structures, making them essential for working with APIs, configuration files, and database responses.
# Nested dictionary — user database
users = {
"alice": {
"name": "Alice Smith",
"age": 28,
"skills": ["Python", "Django"]
},
"bob": {
"name": "Bob Jones",
"age": 32,
"skills": ["React", "Node"]
}
}
# Access nested values
print(users["alice"]["name"]) # Alice Smith
print(users["bob"]["skills"][0]) # React
# Add a new nested entry
users["carol"] = {"name": "Carol Day", "age": 24, "skills": []}
# Update nested value
users["alice"]["age"] = 29
users["alice"]["skills"].append("FastAPI")
# Iterate nested dict
for username, info in users.items():
print(f"{username}: {info['name']}, age {info['age']}")
# Safe nested access with .get()
score = users.get("dave", {}).get("age", "unknown")
print(score) # unknown — dave doesn't exist, no KeyError
Dict Comprehension
Dict comprehension is a concise way to build a new dictionary in one
expression. The syntax
{key_expr: val_expr for item in iterable if condition} is
faster than equivalent loops and directly communicates intent.
# Squares dict: {1: 1, 2: 4, 3: 9, ...}
squares = {x: x**2 for x in range(1, 6)}
print(squares)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# With filter: only even numbers
even_sq = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_sq)
# {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
# Invert a dictionary — swap keys and values
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
# Transform values
words = ["hello", "world", "python"]
lengths= {w: len(w) for w in words}
print(lengths) # {'hello': 5, 'world': 5, 'python': 6}
# From two lists
keys = ["name", "age", "city"]
values = ["Alice", 25, "Vadodara"]
record = {k: v for k, v in zip(keys, values)}
print(record)
# Filter dict — keep only high scores
scores = {"Alice": 90, "Bob": 65, "Carol": 88, "Dave": 72}
honours = {k: v for k, v in scores.items() if v >= 85}
print(honours) # {'Alice': 90, 'Carol': 88}
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all dictionary examples from this chapter directly in your browser with these free Python environments.
-
A dictionary stores key-value pairs in
{key: value}syntax. Keys must be unique and hashable; values can be anything. - As of Python 3.7+, dicts maintain insertion order. Lookup by key is O(1).
-
Access values with
d[key](raisesKeyErrorif absent) ord.get(key, default)(safe, no error). -
Assign to a new key to add it; assign to an existing key to update it. Delete with
del d[key]ord.pop(key). -
d.update(other)merges another dict in-place. Python 3.9+ supportsd | other(new dict) andd |= other(in-place). -
Iterate with
d.keys(),d.values(), ord.items()— all return live view objects. -
setdefault(k, v)is the key method for grouping and counting — retrieves value if key exists, or inserts the default and returns it. -
Nested dicts model hierarchical data (JSON, API responses). Use chained
.get()calls for safe deep access. -
Dict comprehension:
{k: v for k, v in iterable if condition}— builds dicts concisely from existing data.
d[key] raises a
KeyError if the key does not exist — use it
only when you are certain the key is present.
d.get(key) returns
None silently if the key is absent, or a
custom default if you supply one:
d.get(key, default). Use it whenever the key
may be missing to write safe, crash-free code.
d = {"a": 1}
print(d.get("z", 0)) # 0 — safe default
# d["z"] → KeyError
Use d.items() which yields
(key, value) tuples. Combine it with tuple
unpacking in the for loop — this is the most
Pythonic and readable pattern:
for key, value in d.items():
print(f"{key}: {value}")
Alternatives: d.keys() for keys only,
d.values() for values only. Iterating
for k in d: also iterates keys.
d.setdefault(key, default) has two
behaviours:
-
If
keyexists: returns the existing value (does not overwrite it). -
If
keyis absent: insertskey: defaultinto the dict and returnsdefault.
It's most useful for grouping items — you can call
d.setdefault(key, []).append(item) in a loop
without an if-check:
groups = {}
for word in ["apple", "avocado", "banana"]:
groups.setdefault(word[0], []).append(word)
# {'a': ['apple', 'avocado'], 'b': ['banana']}
Both remove a key from the dictionary, but they differ in return value and error handling:
-
del d[key]— removes the key; returns nothing; raisesKeyErrorif absent. -
d.pop(key)— removes the key and returns its value; raisesKeyErrorif absent. -
d.pop(key, default)— returnsdefaultinstead of raising an error when key is absent.
Use pop() when you need the removed value;
use del when you just want to discard it.
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
This works reliably only when all values are unique and hashable. If values are duplicated, later keys will overwrite earlier ones during inversion.
d.get("x", 42) return if key "x" does not
exist?
{v: k for k, v in {"a":1,"b":2}.items()}?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.