Learning Objectives – after this chapter you will be able to:
  • Create dictionaries and access values safely with [] and get().
  • Add, update and delete key–value pairs.
  • Loop through keys, values and items.
  • Use nested dictionaries and dictionary comprehensions.
What is a Dictionary?
  • A dictionary (dict) stores data as key : value pairs inside curly braces: {"name": "Asha", "age": 20}.
  • Values are looked up by key, not by position, which makes look-ups very fast.
  • Keys must be unique and hashable (immutable types such as str, int, tuple). Values can be anything and may repeat.
  • Dictionaries are mutable, and since Python 3.7 they keep items in insertion order.
student = {"name": "Asha", "age": 20, "course": "BCA"}
print(student["name"])
print(student.get("age"))
print(student.get("city"))               # missing key -> None
print(student.get("city", "Not given"))  # with a default

try:
    print(student["city"])
except KeyError as e:
    print("KeyError:", e)

other = dict(name="Ravi", age=21)
print(other, len(other))
Output
Asha
20
None
Not given
KeyError: 'city'
{'name': 'Ravi', 'age': 21} 2
Adding, Updating and Deleting
OperationEffect
d[key] = valueAdds the key, or updates it if it already exists.
d.update(other)Adds/updates many pairs at once.
d.setdefault(key, v)Returns the value; inserts v only if the key is missing.
d.pop(key)Removes the key and returns its value.
d.popitem()Removes and returns the last inserted pair.
del d[key]Deletes the key.
d.clear()Removes all items.
stock = {"pen": 50, "book": 20}
stock["bag"] = 5            # add
stock["pen"] = 45           # update
stock.update({"ink": 12, "book": 18})
print(stock)

removed = stock.pop("bag")
del stock["ink"]
print(stock, "| removed:", removed)
print("pen" in stock, "bag" in stock)   # checks KEYS
Output
{'pen': 45, 'book': 18, 'bag': 5, 'ink': 12}
{'pen': 45, 'book': 18} | removed: 5
True False
Looping Through a Dictionary

keys(), values() and items() return views of the dictionary. Looping over a dictionary directly gives its keys.

marks = {"Maths": 88, "Physics": 76, "English": 91}
for subject in marks:
    print(subject, end=" ")
print()
print(list(marks.values()))
for subject, score in marks.items():
    print(f"{subject:<8}{score}")
print("Topper subject:", max(marks, key=marks.get))
Output
Maths Physics English
[88, 76, 91]
Maths   88
Physics 76
English 91
Topper subject: English
Counting with a Dictionary
text = "banana"
freq = {}
for ch in text:
    freq[ch] = freq.get(ch, 0) + 1
print(freq)
Output
{'b': 1, 'a': 3, 'n': 2}
Nested Dictionaries and Comprehensions
students = {
    101: {"name": "Asha", "marks": 82},
    102: {"name": "Ravi", "marks": 67},
}
print(students[102]["name"])
students[101]["marks"] += 5
print(students[101])

squares = {n: n * n for n in range(1, 6)}
passed = {sid: s["name"] for sid, s in students.items() if s["marks"] >= 70}
print(squares)
print(passed)
Output
Ravi
{'name': 'Asha', 'marks': 87}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{101: 'Asha'}
Key Takeaways
  • Dictionaries map unique, hashable keys to values and keep insertion order (3.7+).
  • d[key] raises KeyError for missing keys; d.get(key, default) does not.
  • Loop with items(); build dictionaries with comprehensions.
Video : Dictionary
Question / Answer (15 questions)

Answer : A dictionary is a mutable collection of key–value pairs written inside curly braces, e.g. {"name": "Asha", "age": 20}. Values are accessed by their keys rather than by position.

Answer : Keys must be unique and hashable (immutable types such as str, int, float or tuples of immutable items). Lists, sets and dictionaries cannot be keys. Values have no such restriction.

Answer : Since Python 3.7, dictionaries preserve insertion order as part of the language specification, so items are returned in the order they were added.

Answer : d["key"] raises KeyError if the key does not exist. d.get("key") returns None (or a supplied default, e.g. d.get("key", 0)) instead of raising an error.

Answer : Assign to the key: d["city"] = "Bhopal". If the key exists, its value is replaced; otherwise a new pair is added. update() adds or replaces several pairs at once.

Answer : pop(key) removes the given key and returns its value. popitem() removes and returns the last inserted (key, value) pair. del d[key] deletes a key without returning anything.

Answer : They return view objects that show the dictionary’s keys, values and (key, value) pairs respectively. Views reflect later changes to the dictionary and can be looped over or converted with list().

Answer : It checks whether a KEY is present: "pen" in stock. To check values use value in d.values().

Answer : freq = {}; for ch in text: freq[ch] = freq.get(ch, 0) + 1. For "banana" this gives {'b': 1, 'a': 3, 'n': 2}.

Answer : d.setdefault(key, value) returns the value of key if it exists; if it does not, it inserts key with the given value and returns that value.

Answer : A dictionary whose values are themselves dictionaries. Use chained keys: students[102]["name"] returns the name stored for student 102.

Answer : {n: n * n for n in range(1, 6)} produces {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}.

Answer : max(d, key=d.get) returns the key whose value is largest. For marks = {"Maths": 88, "Physics": 76, "English": 91} it returns "English".

Answer : Keys are unique, so the later value overwrites the earlier one: {"a": 1, "a": 2} becomes {'a': 2}.

Answer : Dictionaries are implemented as hash tables. A key’s hash is used to find its location directly, so look-ups take roughly constant time on average regardless of the dictionary’s size.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. What does {"a": 1}.get("b", 0) return?

Show Answer

Correct Answer : C. 0
The key is missing, so the default 0 is returned.

Q2. Which of these can NOT be a dictionary key?

Show Answer

Correct Answer : D. [1, 2]
Lists are mutable and unhashable.

Q3. d = {"x": 1}; d["x"] = 5. What is d?

Show Answer

Correct Answer : A. {'x': 5}
Assigning to an existing key updates its value.

Q4. Looping directly over a dictionary (for k in d) gives its:

Show Answer

Correct Answer : B. Keys
Iteration over a dict yields its keys.

Q5. Which method removes a key and returns its value?

Show Answer

Correct Answer : D. pop()
pop(key) removes the key and returns its value; dict has no remove().

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Python Software Foundation. (n.d.). Data Structures. In The Python Tutorial. https://docs.python.org/3/tutorial/datastructures.html
  2. Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
  3. Python Software Foundation. (n.d.). Glossary. Python 3 Documentation. https://docs.python.org/3/glossary.html
  4. Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
  5. Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.
  6. Matthes, E. (2023). Python Crash Course (3rd ed.). No Starch Press.