This guide walks you through Python dictionaries in the order you usually need them: syntax, creating dicts, reading and updating values, looping, membership checks, removal, copying, and a compact methods table.
student = {
"name": "Alice",
"age": 21,
"course": "Python",
}
print(student)A dictionary stores data as key-value pairs inside curly braces {}. Each key maps to one value, and you look up values by key—not by numeric index like a Python list. In modern Python, dicts preserve insertion order when you iterate or print them, while the tutorial still stresses that lookups are keyed, not positional.
When you pass a plain dict to any() or all(), Python walks the keys; see Python any() and all() if you use those helpers on mappings. For adding keys in depth, see Python add to dictionary; for nested trees, see nested dictionary in Python; for merging dicts, see extend dictionary and merge dictionaries.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
What is a dictionary in Python?
A dictionary (dict) is a mutable mapping: a collection of keys, each associated with a value. Keys in one dict are unique; assigning again overwrites the previous value. Values can be any Python object, including lists or other dicts.
Before Python 3.7, people sometimes used collections.OrderedDict when insertion order mattered; today the built-in dict also keeps insertion order, so beginners can rely on normal dict unless a library specifically requires OrderedDict.
Python dictionary syntax
- Literals use curly braces
{}, withkey: valuepairs separated by commas. - Keys must be hashable (strings, numbers, tuples of immutables, etc.); values can be anything.
- Keys are unique:
{"a": 1, "a": 2}ends up as{"a": 2}. - The constructor
dict(...)does not usekey: valueinside the parentheses; usedict(name=value, ...)for string keys that are valid identifiers, or pass a list of pairs (see below).
Create a dictionary in Python
Use braces and string keys for a readable record:
cars = {
"hyundai": "i10",
"maruti": "swift",
"honda": "city",
}
print(cars["maruti"])You should see swift.
Create an empty dictionary
Two common spellings:
a = {}
b = dict()
print(type(a), len(a), len(b))Both create an empty dict. Use {} for an empty dict; set() is the empty set, not {}.
Create a dictionary using dict()
Keyword arguments become string keys (identifiers only). For arbitrary keys, pass an iterable of (key, value) pairs:
cars = dict(hyundai="i10", maruti="swift", honda="city")
also = dict([("hyundai", "i10"), ("maruti", "swift"), ("honda", "city")])
print(cars == also)You should see True. You cannot write dict(hyundai: "i10")—colons belong in {} literals, not in the dict() call.
Access dictionary values using keys
Use square brackets. If the key is missing, Python raises KeyError.
user = {"name": "Ada", "score": 100}
print(user["name"])You should see Ada.
Access values safely using get()
dict.get(key, default) returns the value if the key exists, otherwise None or your default—no exception.
cfg = {"host": "localhost"}
print(cfg.get("port"))
print(cfg.get("port", 8080))You should see None on the first line and 8080 on the second.
Add item to a dictionary
Assign to a new key:
user = {"name": "Bob"}
user["city"] = "Delhi"
print(user)You should see city in the printed dict.
Update item in a dictionary
Assign to an existing key to replace its value:
user = {"name": "Bob", "age": 20}
user["age"] = 21
print(user["age"])You should see 21.
Add or update multiple items using update()
update() merges another mapping or iterable of pairs into the dict in place. Existing keys get new values from the right-hand data.
user = {"name": "Kim", "age": 30}
user.update({"age": 31, "city": "Seoul"})
print(user)You should see age updated and city added. This is map-style growth, not the same as list.append or list.extend.
Check if a key exists in dictionary
Use in or not in:
user = {"name": "Lee"}
print("name" in user, "age" in user)You should see True then False.
Loop through a dictionary
Loop through keys
Calling keys() is optional; iterating the dict iterates keys by default.
scores = {"ada": 10, "bob": 20}
for name in scores:
print(name)You should see ada and bob on separate lines in insertion order.
Loop through values
scores = {"ada": 10, "bob": 20}
for value in scores.values():
print(value)You should see 10 then 20.
Loop through keys and values
scores = {"ada": 10, "bob": 20}
for name, value in scores.items():
print(name, value)You should see two lines pairing each name with its score.
Remove item from a dictionary
Remove item using del
del d[key] drops a key; missing keys raise KeyError.
d = {"a": 1, "b": 2}
del d["a"]
print(d)You should see only b.
Remove item using pop()
pop(key) removes the key and returns its value; you can pass a default to avoid errors when the key is missing.
d = {"a": 1, "b": 2}
print(d.pop("a"), d.pop("z", None))
print(d)You should see 1, None, then {'b': 2}.
Remove last item using popitem()
In Python 3.7 and newer, popitem() removes and returns the last inserted (key, value) pair as a tuple (not a random pair).
d = {"x": 1}
d["y"] = 2
print(d.popitem())
print(d)You should see ('y', 2) removed last, then the dict with only x.
Clear all items from a dictionary
clear() removes every key-value pair; the object stays the same dict instance.
d = {"a": 1}
d.clear()
print(d, len(d))You should see {} and length 0.
Copy a dictionary
copy() makes a shallow copy: the outer dict is new, but values that are mutable objects are shared with the original.
inner = [1, 2]
a = {"k": inner}
b = a.copy()
b["k"].append(3)
print(a["k"], b["k"])Both lists show [1, 2, 3]. For a fully independent nested structure, use copy.deepcopy from the copy module.
Common Python dictionary methods
| Method | Use |
|---|---|
dict.get(key) |
Get value without raising on missing key |
dict.keys() |
View of keys |
dict.values() |
View of values |
dict.items() |
View of (key, value) pairs |
dict.update(other) |
Add or overwrite many keys in place |
dict.pop(key) |
Remove key and return its value |
dict.popitem() |
Remove and return last inserted pair (3.7+) |
dict.clear() |
Remove all items |
dict.copy() |
Shallow copy of the dict |
dict.setdefault(key, default) |
Return value if key exists, else set default and return it |
setdefault is handy when building tallies or caches. To present keys in sorted order, see sort dictionary by key or sort dictionary by value.
counts = {}
for ch in "aba":
counts[ch] = counts.setdefault(ch, 0) + 1
print(counts)You should see {'a': 2, 'b': 1}.
Common mistakes with Python dictionaries
- Using
()instead of{}for a dict literal—you get a tuple, not a mapping. - Writing
dict(hyundai: "i10")with colon syntax; usedict(hyundai="i10")or pairs like[("hyundai", "i10"), ...]. - Using
d[key]when the key might be missing; you getKeyErrorunless you guard withinor useget. - Expecting duplicate keys to keep two values—the last one wins.
- Treating dicts like lists:
d[0]is not the “first value” unless the key is actually0. - Believing
popitem()is random on current Python; it pops the last inserted item in the usual case. - Confusing
update()withappend/extendon lists; dicts merge by key, not by position. - Using mutable values (like lists) as keys; keys must be hashable.
To confirm an object is a dict, type(x) is dict or isinstance(x, dict) is enough for most scripts—no need for a long sidebar on typing here.
Python dictionary quick reference table
| Need | Example |
|---|---|
| Create dictionary | user = {"name": "Alice", "age": 21} |
| Create empty dictionary | user = {} |
Create using dict() |
user = dict(name="Alice", age=21) |
| Access value | user["name"] |
| Access safely | user.get("name") |
| Add item | user["city"] = "Delhi" |
| Update item | user["age"] = 22 |
| Add many items | user.update({"city": "Delhi"}) |
| Check key | "name" in user |
| Loop items | for key, value in user.items(): |
| Remove item | user.pop("age") |
| Clear dictionary | user.clear() |
Summary
Dictionaries map unique keys to values with {} syntax or the dict() constructor. You read with [] or get, write with assignment or update, loop with .items(), test membership with in, and remove with del, pop, or popitem(). Modern dicts keep insertion order; use keys for access, not list-style positions. For shallow copies use copy(); reach for deepcopy when nested mutables must diverge. Compare containers in list vs set vs tuple vs dictionary.

