Chapter 09
Python Dictionaries
4 topics · 1 sections · beginner-friendly study notes · Updated
A dictionary maps unique keys to values.
This chapter covers creating and updating dictionaries, the main dictionary methods, and clear comparisons with list, set and tuple.
Dictionaries give fast lookup by name and model real-world records like JSON.
JSON data, word counts, caches, configuration, database rows.
Python Dictionary
A dictionary is a mutable collection of key-value pairs written as {key: value}. Keys must be unique and hashable; values can be anything. Since Python 3.7, a dictionary remembers insertion order.
In short: Like a real dictionary or phone book: you look up a word (key) to get its meaning (value).
Think about it
Real data comes in labelled form, and dictionaries make that labelled access fast and readable. A student record: {"name": "Ann", "roll": 7, "marks": [80, 90]}.
Create with `{...
}, dict(name="Ann", age=20), dict([("a", 1)]) or dict.
fromkeys(keys, default)`.
Access with d[key] (KeyError if missing) or `d.
get(key, default)` (never raises).
Assigning to a new key adds it; assigning to an existing key replaces the value.
Remove with del d[key] or pop.
Membership with in checks KEYS.
Looping: for k in d, `for v in d.
values(), for k, v in d.
items()`.
Do not add or remove keys while looping over a dictionary because it raises RuntimeError; iterate over list(d) instead.
Dictionary comprehension: {x: x*x for x in range(4)}.
Nested dictionaries model JSON: d["user"]["name"].
Lookup, insert and delete are O(1) on average because of hashing.
Key points
- Key: Unique, hashable identifier.
- Value: Data associated with a key.
- Item: A (key, value) pair.
- Nested dictionary: A dictionary whose values are dictionaries.
Read more
Example
CodeCreating and using dictionaries:
student = {"name": "Ann", "age": 20, "city": "Pune"}
print(student["name"]) # Ann
print(student.get("phone")) # None
print(student.get("phone", "N/A")) # N/A
student["age"] = 21 # update
student["grade"] = "A" # add new key
del student["city"] # delete
print(student) # {'name': 'Ann', 'age': 21, 'grade': 'A'}
print("name" in student, "Ann" in student) # True False (keys only)
for k in student:
print(k, student[k])
for k, v in student.items():
print(k, "->", v)
squares = {x: x * x for x in range(4)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9}
print(dict(a=1, b=2)) # {'a': 1, 'b': 2}
users = {"u1": {"name": "Li", "tags": ["a", "b"]}}
print(users["u1"]["tags"][0]) # a
for k in list(student): # safe way to delete while looping
if k == "age":
del student[k]Python Dictionary Methods
Dictionary methods read, update and remove items. The main ones are keys, values, items, get, setdefault, update, pop, popitem, clear, copy and fromkeys.
In short: They are ready-made tools to see all keys or values, read safely, merge dictionaries and delete entries.
Think about it
Counting, grouping and merging with these methods is the most common dictionary work in exams and jobs. Counting how many times each word appears in a paragraph.
keys(), values() and items() return live VIEW objects that reflect later changes; wrap them in list() for a snapshot.
get(k, default) reads safely.
setdefault(k, default) returns the value if k exists, otherwise inserts k with default and returns it (great for grouping).
update(other) merges another dictionary or key-value pairs, overwriting duplicate keys.
pop(k, default) removes and returns a value (KeyError if no default); popitem() removes the LAST inserted pair (3.7+); clear() empties; copy() is shallow.
`dict.
fromkeys(keys, value)` shares the same value object, so avoid a mutable default like a list.
Python 3.9 adds d1 | d2 for a merged copy and d1 |= d2 to merge in place.
Sorting: `sorted(d.
items(), key=lambda kv: kv[1])` sorts by value.
Key points
- View object: Dynamic window on keys, values or items.
- setdefault: Get a key, or insert a default if missing.
- popitem: Remove and
returnthe last inserted pair.
Read more
Example
CodeDictionary methods in use:
d = {"a": 1, "b": 2}
print(list(d.keys())) # ['a', 'b']
print(list(d.values())) # [1, 2]
print(list(d.items())) # [('a', 1), ('b', 2)]
print(d.get("z", 0)) # 0
print(d.setdefault("c", 3)) # 3 (inserted)
print(d) # {'a': 1, 'b': 2, 'c': 3}
d.update({"b": 20, "d": 4})
print(d) # {'a': 1, 'b': 20, 'c': 3, 'd': 4}
print(d.pop("a")) # 1
print(d.pop("zzz", None)) # None (no KeyError)
print(d.popitem()) # ('d', 4) last inserted
print(d) # {'b': 20, 'c': 3}
print(dict.fromkeys(["x", "y"], 0)) # {'x': 0, 'y': 0}
merged = {"a": 1} | {"b": 2} # Python 3.9+
print(merged) # {'a': 1, 'b': 2}
# count letters
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}
# group words by length
groups = {}
for w in ["hi", "yo", "cat"]:
groups.setdefault(len(w), []).append(w)
print(groups) # {2: ['hi', 'yo'], 3: ['cat']}
marks = {"ann": 70, "raj": 90, "li": 80}
print(sorted(marks.items(), key=lambda kv: kv[1], reverse=True))
# [('raj', 90), ('li', 80), ('ann', 70)]
d.clear()
print(d) # {}keys / values / items
Return views for looping and converting.
get / setdefault
Safe reading and insert-if-missing.
update / | merge
Combine dictionaries; later values win.
pop / popitem / clear / del
Remove one key, the last pair, or everything.
Difference between List and Dictionary in Python
A list stores items accessed by numeric position (index), while a dictionary stores key-value pairs accessed by key. Lists use [], dictionaries use {key: value}.
In short: List = lockers numbered 0, 1, 2. Dictionary = lockers with names on them.
Think about it
Choosing the correct structure decides if code is simple and fast. List: queue of tokens in a bank. Dictionary: account number to balance.
Access: lst[2] versus d["name"].
Order: both keep insertion order in modern Python, but a list is positional and a dictionary is by key.
Duplicates: a list allows duplicate items; a dictionary has unique keys.
Lookup speed: searching a list with in is O(n); searching a dictionary key is O(1) on average.
Memory: a dictionary uses more memory because of hashing.
Slicing and sort() exist for lists but not for dictionaries.
Keys must be hashable; list items can be anything.
Use a list for an ordered sequence of similar things, and a dictionary when you need to find data by a label.
Key points
- Positional access: Finding an item by its index.
- Key-based access: Finding a value by its key.
Read more
Example
CodeList vs dictionary:
lst = ["Ann", "Raj", "Li"]
d = {101: "Ann", 102: "Raj", 103: "Li"}
print(lst[1]) # Raj (by index)
print(d[102]) # Raj (by key)
lst.append("Sam") # add at end
d[104] = "Sam" # add by key
print(["a", "a"]) # duplicates allowed in list
print({"a": 1, "a": 2}) # {'a': 2} duplicate key overwritten
print(lst[1:3]) # slicing works on list
# d[1:3] # TypeError: unhashable type: 'slice'
print("Li" in lst) # searches every item (slow for big lists)
print(103 in d) # hashed key lookup (fast)Difference between List, Set, Tuple, and Dictionary in Python
List [] is ordered and mutable, tuple () is ordered and immutable, set {} is unordered with unique items, and dictionary {k: v} stores key-value pairs with unique keys.
In short: List = editable row. Tuple = locked row. Set = bag of unique items. Dictionary = labelled boxes.
Think about it
This four-way table is a frequent interview question and helps you pick the right container. Cart items (list), GPS point (tuple), unique visitors (set), user profile (dictionary).
Ordered: list, tuple and dictionary (3.7+) keep order; set does not.
Mutable: list, set, dictionary yes; tuple no.
Duplicates: list and tuple allow them; set does not; dictionary keys must be unique.
Indexing: list and tuple by number; dictionary by key; set none.
Empty creation: [], (), set(), {}.
Hashable: tuple (of hashables) can be a dict key or set item; list, set and dict cannot.
Typical use
list for changing sequences, tuple for fixed records, set for uniqueness and membership, dictionary for labelled lookup.
Convert between them with list(), tuple(), set() and dict().
Key points
Read more
Example
CodeThe four collections together:
data = [1, 2, 2, 3]
print(data) # list : [1, 2, 2, 3]
print(tuple(data)) # tuple : (1, 2, 2, 3)
print(set(data)) # set : {1, 2, 3}
print(dict(zip("abc", data))) # dict : {'a': 1, 'b': 2, 'c': 2}
print(type([]), type(()), type(set()), type({}))
# Quick feature check
# list tuple set dict
# ordered yes yes no yes (3.7+)
# mutable yes no yes yes
# duplicates yes yes no keys unique
# index yes yes no by key
# literal [] () {1,2} {k: v}
for coll in ([1, 2], (1, 2), {1, 2}, {1: "a", 2: "b"}):
print(type(coll).__name__, len(coll))Solved examples
Count characters in "hello" using a dictionary.
Character-count dictionary
Formula Applied:—Approach note: collections.Counter does the same in one line.
Given marks = {"ann": 70, "raj": 90, "li": 80}, find the name with the highest marks.
A name
Formula Applied:—Approach note: Use marks.items() with a lambda for more complex sorting.
What is the output of {"a": 1, "b": 2, "a": 3}?
Resulting dictionary
Formula Applied:—Approach note: Position of a stays where it first appeared.
scores = {"ann": 80, "bob": 95, "li": 70}. Print the name with the highest score.
Name of top scorer
Formula Applied:—Approach note: max(dict, key=dict.get) returns the key of the largest value.
Real-world applications
Using Python Dictionaries in real projects
JSON data, word counts, caches, configuration, database rows.
Common mistakes
❌ Myth: "x" in d checks the values.
Why this is wrong: Membership tests keys.
✅ Verified Truth: Use x in d.values() for values.
⚠️ Exam Tip: Frequent trick question.
❌ Myth: Dictionaries are unordered in Python 3.
Why this is wrong: Since 3.7 they keep insertion order.
✅ Verified Truth: Sets are still unordered.
⚠️ Exam Tip: State the version in interviews.
❌ Myth: A list can be a dictionary key.
Why this is wrong: Lists are unhashable.
✅ Verified Truth: Use a tuple as the key.
⚠️ Exam Tip: Keys must be immutable.
Revision notes
A dictionary maps unique keys to values. This chapter covers creating and updating dictionaries, the main dictionary methods, and clear comparisons with list, set and tuple.
High-Yield Quick Revision Points
- Dict: key to value, unique hashable keys, ordered (3.7+)
- d[k] raises KeyError; d.get(k, default) does not
- in checks keys
- update, pop, popitem, setdefault, items
- List by index, dict by key
- List [] / tuple () / set {} unique / dict {k: v}
Practice questions
What does d.get("z") return if "z" is missing?
"b" in {"a": 1, "b": 2} checks:
Which gives the last inserted pair?
Which collection is ordered AND immutable?
Result of {"a": 1}.update({"a": 5})?
Which structure is best for fast lookup by name?