How does your phone find "Mom" among hundreds of contacts instantly? It doesn't scan position 0, 1, 2, 3โฆ โ it looks up the name and jumps straight to the number! Lists and tuples store values by position, but in real life we often want to find a value by a meaningful name: a roll number โ a student, a word โ its meaning, a country โ its capital. Python's dictionary does exactly this. This chapter shows how to create a dictionary, the rules for its keys, how to add, change and delete items, what keys(), values(), items(), get(), update() and pop() do, and how to count the frequency of characters with a dictionary.
Focus especially on rules for keys, accessing with [ ] vs get(), adding vs updating items, keys() / values() / items(), pop() vs popitem() vs del, and the character-frequency program โ revise these carefully.
12.1 ๐ Introduction
A dictionary is a mutable collection of key : value pairs enclosed in curly braces { }. Each key is linked (mapped) to a value, and you use the key to get the value โ not an index number.
student = {"roll": 101, "name": "Riya", "marks": 92.5}
print(student["name"]) # Riya
student = { "roll" : 101 , "name" : "Riya" , "marks" : 92.5 }
โ โ
key value โ each key : value is ONE item
Key
The unique "label" used to look up a value; must be of an IMMUTABLE type
str or int or tupleValue
The data linked to a key; can be of ANY type and can repeat
Any typeMutable
Items can be added, changed and deleted after the dictionary is created
ChangeableMapping
Values are accessed by KEY, not by position; there is no index 0 or 1
Key-based accessAnalogy: A dictionary is exactly like an English dictionary ๐ โ you look up a word (key) to find its meaning (value). You never say "give me the meaning at page 237, line 4"; you just look up the word!
In Python 3.7 and later, a dictionary remembers the order in which items were inserted, so it prints in that order. But you still cannot access items by position โ student[0] looks for a key 0, not "the first item".
12.2 ๐ ๏ธ Creating a Dictionary
# 1. Using curly braces
capitals = {"India": "New Delhi", "Japan": "Tokyo", "France": "Paris"}
# 2. An empty dictionary, filled later
marks = {}
marks["Maths"] = 95
marks["Physics"] = 88
print(marks) # {'Maths': 95, 'Physics': 88}
# 3. Using dict() with keyword arguments (keys become strings)
emp = dict(name="Aman", age=30, city="Pune")
print(emp) # {'name': 'Aman', 'age': 30, 'city': 'Pune'}
# 4. Using dict() with a list of (key, value) pairs
d = dict([(1, "one"), (2, "two")])
print(d) # {1: 'one', 2: 'two'}
# 5. Using dict.fromkeys() โ same value for many keys
scores = dict.fromkeys(["Riya", "Aman", "Zoya"], 0)
print(scores) # {'Riya': 0, 'Aman': 0, 'Zoya': 0}
{} creates an empty dictionary, NOT an empty set or tuple. type({}) is <class 'dict'>.
12.2.1 Rules for Keys ๐
- Keys must be unique โ if a key is repeated, the last value wins.
- Keys must be of an immutable type โ
int,float,str,boolor atuple(of immutable values). - A list or another dictionary can NEVER be a key (they are mutable) โ
TypeError: unhashable type. - Values have no restrictions โ any type, duplicates allowed.
d = {"a": 1, "b": 2, "a": 3}
print(d) # {'a': 3, 'b': 2} โ duplicate key: last value wins
points = {(0, 0): "origin", (2, 3): "P"} # โ
tuple keys are allowed
print(points[(2, 3)]) # P
# bad = {[1, 2]: "list key"} # โ TypeError: unhashable type: 'list'
"Can a list be used as a key in a dictionary? Why or why not?" โ 2-mark question!
Answer: No. Dictionary keys must be of an immutable (hashable) type such as int, str or tuple. A list is mutable, so using it as a key raises TypeError: unhashable type: 'list'. A tuple of immutable values can be used instead.
12.3 ๐ Accessing Values
12.3.1 Using Square Brackets d[key]
student = {"roll": 101, "name": "Riya", "marks": 92.5}
print(student["marks"]) # 92.5
# print(student["age"]) # โ KeyError: 'age'
12.3.2 Using get() โ The Safe Way
student = {"roll": 101, "name": "Riya", "marks": 92.5}
print(student.get("name")) # Riya
print(student.get("age")) # None โ no error!
print(student.get("age", "N/A")) # N/A โ your own default value
d[key] vs d.get(key) โ The Critical Comparison:
| Feature | d[key] |
d.get(key, default) |
|---|---|---|
| Key present | Returns its value | Returns its value |
| Key absent | Raises KeyError |
Returns None (or the given default) |
| Can be used to add/update? | โ
Yes: d[key] = value |
โ No โ it only reads |
12.3.3 Checking a Key with in
The membership operator in checks KEYS only, never values.
student = {"roll": 101, "name": "Riya"}
print("name" in student) # True
print("Riya" in student) # False โ "Riya" is a VALUE, not a key
print("Riya" in student.values()) # True โ check the values explicitly
"Differentiate between accessing a value using d[key] and d.get(key)." โ 2-mark question!
Answer: Both return the value for an existing key. If the key does not exist, d[key] raises a KeyError, whereas d.get(key) returns None (or the default value passed as the second argument) without any error.
12.4 โ๏ธ Adding, Updating and Deleting Items
12.4.1 Adding and Updating โ Same Syntax! ๐
d[key] = value updates the value if the key exists, and adds a new item if it doesn't.
stock = {"pen": 50, "pencil": 30}
stock["pen"] = 45 # key exists โ value UPDATED
stock["eraser"] = 20 # new key โ item ADDED
print(stock) # {'pen': 45, 'pencil': 30, 'eraser': 20}
d[key] = value
โ
โโโ key already present? โโโบ value is REPLACED (update)
โโโ key not present? โโโบ new item is ADDED (insert)
12.4.2 Deleting Items ๐๏ธ
| Way | Description | Example (d = {"a": 1, "b": 2, "c": 3}) |
Result |
|---|---|---|---|
del d[key] |
Deletes the item with that key; KeyError if absent | del d["b"] |
{'a': 1, 'c': 3} |
d.pop(key) |
Deletes the item and returns its value; KeyError if absent | x = d.pop("a") |
x = 1, d = {'b': 2, 'c': 3} |
d.pop(key, default) |
Returns default instead of an error if the key is absent |
d.pop("z", 0) |
0 (d unchanged) |
d.popitem() |
Deletes and returns the last inserted item as a tuple | d.popitem() |
('c', 3), d = {'a': 1, 'b': 2} |
d.clear() |
Removes all items | d.clear() |
{} |
del d |
Deletes the whole dictionary variable | del d |
d no longer exists |
pop(key)
Removes the item with the given KEY and RETURNS its value
Returns the valuepopitem()
Removes the LAST inserted item and RETURNS it as a (key, value) tuple
Returns a tupledel d[key]
A statement; removes the item with the given key and returns nothing
Returns nothing"Differentiate between pop() and popitem()." โ 2-mark question!
Answer: pop(key) removes the item with the specified key and returns its value. popitem() takes no argument; it removes the last inserted item and returns it as a (key, value) tuple.
12.5 ๐ถ Traversing a Dictionary
A for loop over a dictionary gives you its KEYS one by one.
marks = {"Maths": 95, "Physics": 88, "Chemistry": 91}
for sub in marks: # 1. loop over keys
print(sub, "โ", marks[sub])
for sub, m in marks.items(): # 2. loop over (key, value) pairs
print(f"{sub}: {m}")
total = 0
for m in marks.values(): # 3. loop over values only
total += m
print("Total:", total) # Total: 274
Maths โ 95
Physics โ 88
Chemistry โ 91
Maths: 95
Physics: 88
Chemistry: 91
Total: 274
12.6 ๐งฐ Dictionary Functions and Methods
12.6.1 Viewing Keys, Values and Items ๐
| Method | Returns | Example (d = {"x": 10, "y": 20}) |
Result |
|---|---|---|---|
d.keys() |
All the keys | d.keys() |
dict_keys(['x', 'y']) |
d.values() |
All the values | d.values() |
dict_values([10, 20]) |
d.items() |
All the items as (key, value) tuples | d.items() |
dict_items([('x', 10), ('y', 20)]) |
d = {"x": 10, "y": 20}
print(list(d.keys())) # ['x', 'y']
print(list(d.values())) # [10, 20]
print(list(d.items())) # [('x', 10), ('y', 20)]
keys(), values() and items() return special view objects. Wrap them in list() when you want a normal list to print, index or sort.
12.6.2 Other Useful Methods and Functions ๐ง
| Function / Method | Description | Example | Result |
|---|---|---|---|
len(d) |
Number of items (key-value pairs) | len({"a": 1, "b": 2}) |
2 |
d.update(d2) |
Adds the items of d2 to d; overwrites values of common keys |
{"a": 1, "b": 2}.update({"b": 9, "c": 3}) |
d becomes {'a': 1, 'b': 9, 'c': 3} |
d.setdefault(k, v) |
Returns d[k] if k exists; otherwise adds k : v and returns v |
{"a": 1}.setdefault("b", 5) |
returns 5; adds 'b': 5 |
d.copy() |
Returns a shallow copy (a new dictionary) | d2 = d.copy() |
independent copy |
dict.fromkeys(seq, v) |
New dictionary with keys from seq, all with value v (default None) |
dict.fromkeys("ab") |
{'a': None, 'b': None} |
max(d) / min(d) |
Largest / smallest KEY | max({3: "c", 7: "a"}) |
7 |
sorted(d) |
A sorted list of KEYS | sorted({"b": 1, "a": 2}) |
['a', 'b'] |
prices = {"apple": 120, "banana": 40, "mango": 90}
print(max(prices)) # mango โ max KEY (alphabetical)
print(max(prices.values())) # 120 โ max VALUE
print(sorted(prices)) # ['apple', 'banana', 'mango']
print(sorted(prices.values())) # [40, 90, 120]
A = {"x": 1}
B = A # alias โ same dictionary
C = A.copy() # a separate copy
B["y"] = 2
print(A) # {'x': 1, 'y': 2} โ changed through the alias
print(C) # {'x': 1}
max(), min() and sorted() work on the KEYS of a dictionary by default โ not the values! Use max(d.values()) for the largest value. And, just like lists, B = A makes an alias; use A.copy() for an independent copy.
12.7 ๐ช Nested Dictionaries
A dictionary's values can themselves be dictionaries (or lists), which is perfect for storing records.
students = {
101: {"name": "Riya", "marks": 92},
102: {"name": "Aman", "marks": 85},
}
print(students[102]["name"]) # Aman
students[101]["marks"] = 95 # update a nested value
for roll, info in students.items():
print(roll, info["name"], info["marks"])
Aman
101 Riya 95
102 Aman 85
12.8 โ๏ธ List vs Dictionary
| Feature | List | Dictionary |
|---|---|---|
| Brackets | [ ] |
{ } |
| Stores | Values only | Key : value pairs |
| Access by | Integer index (position) | Key (any immutable value) |
| Duplicates | Values can repeat | Keys must be unique; values can repeat |
in checks |
Values | Keys |
| Best for | An ordered collection of similar items | Looking up data by a name or ID |
"Differentiate between a list and a dictionary." โ 2-mark question!
Answer: A list is an ordered collection of values accessed by an integer index, written in [ ]. A dictionary is a collection of key : value pairs accessed by keys, written in { }; its keys must be unique and immutable.
12.9 ๐ป Important Dictionary Programs
Code Example: char_frequency.py
# Count how many times each character appears in a string
text = input("Enter a string: ")
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
# Input: banana โ {'b': 1, 'a': 3, 'n': 2}
The same program using get() โ shorter!
text = "mississippi"
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
print(freq) # {'m': 1, 'i': 4, 's': 4, 'p': 2}
freq.get(ch, 0) + 1 works ๐ง If ch is already a key, get() returns its current count; if not, it returns 0. Adding 1 and storing it back either starts a new count at 1 or increases the old one โ no if-else needed!
Code Example: word_frequency.py
# Count the frequency of each word in a sentence
sentence = "the cat and the hat and the bat"
count = {}
for word in sentence.split():
count[word] = count.get(word, 0) + 1
for word, c in count.items():
print(word, ":", c)
the : 3
cat : 1
and : 2
hat : 1
bat : 1
Code Example: employee_salary.py
# Create a dictionary of employees and their salaries, then use it
n = int(input("How many employees? "))
emp = {}
for i in range(n):
name = input("Enter name: ")
salary = float(input("Enter salary: "))
emp[name] = salary
print("\nEmployee Salary")
for name in emp:
print(name, " ", emp[name])
search = input("Enter a name to search: ")
if search in emp:
print(search, "earns", emp[search])
else:
print(search, "not found")
How many employees? 2
Enter name: Aman
Enter salary: 45000
Enter name: Riya
Enter salary: 52000
Employee Salary
Aman 45000.0
Riya 52000.0
Enter a name to search: Riya
Riya earns 52000.0
Code Example: topper.py
# Find the student with the highest marks
marks = {"Riya": 92, "Aman": 85, "Zoya": 97, "Kabir": 88}
topper = ""
highest = -1
for name, m in marks.items():
if m > highest:
highest = m
topper = name
print("Topper:", topper, "with", highest, "marks")
# Topper: Zoya with 97 marks
Code Example: invert_dictionary.py
# Swap keys and values
country_code = {"IN": "India", "JP": "Japan", "FR": "France"}
code_of = {}
for code, country in country_code.items():
code_of[country] = code
print(code_of)
# {'India': 'IN', 'Japan': 'JP', 'France': 'FR'}
"Count the number of times a character appears in a string" and "Create a dictionary of employee names and salaries and access them" are the suggested practical programs for dictionaries in the CBSE syllabus โ expect one as a 3-mark question. Practise both the if-else version and the get() version of the frequency program.
โ ๏ธ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
โ d[0] gives the first item |
There is no positional index | โ
d[0] looks for the KEY 0 |
| โ A list can be a key | Keys must be immutable | โ
TypeError: unhashable type: 'list'; use a tuple |
| โ Duplicate keys store two values | Keys are unique | โ The last value overwrites the earlier one |
โ d["x"] returns None if the key is missing |
That's get() |
โ
d["x"] raises KeyError; d.get("x") returns None |
โ "Riya" in d checks values |
in checks keys only |
โ
Use "Riya" in d.values() |
โ max(d) gives the largest value |
It works on keys | โ
Use max(d.values()) |
โ len(d) counts keys AND values separately |
It counts items (pairs) | โ
len({"a": 1, "b": 2}) is 2 |
โ popitem() removes a random item |
Not in Python 3.7+ | โ It removes the LAST inserted item |
โ B = A copies a dictionary |
It creates an alias | โ
Use B = A.copy() |
๐ Quick Revision
Dictionary Basics:
- A mutable collection of key : value pairs in
{ } - Keys โ unique and immutable (int, str, tuple); values โ anything
- Access by key:
d[key](KeyError if missing) ord.get(key, default)(no error) d[key] = valueโ updates if the key exists, adds if notinchecks keys ยท aforloop gives keys
Methods at a Glance:
| Category | Methods / Functions |
|---|---|
| Create | {}, dict(), dict.fromkeys(seq, v) |
| View | keys(), values(), items() |
| Read | get(k, default), setdefault(k, v) |
| Add / merge | d[k] = v, update(d2) |
| Delete | pop(k), popitem() (last item), clear(), del d[k], del d |
| Copy | copy() |
| Functions | len(), max() / min() / sorted() (on keys) |
Frequency pattern: freq[x] = freq.get(x, 0) + 1
๐ฏ Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) What is the output of print(len({"a": 1, "b": 2, "a": 3}))?
โ 2 (the duplicate key "a" is stored only once)
b) Which method returns the value for a key without raising an error if the key is missing?
โ get()
c) What does popitem() return?
โ The last inserted item as a (key, value) tuple
d) What will sorted({"b": 2, "c": 1, "a": 3}) return?
โ ['a', 'b', 'c']
e) Name any two data types that can be used as dictionary keys.
โ int and str (also tuple, float, bool)
Q2: Output Based [2 marks]
Q: Write the output of the following code:
d = {1: "one", 2: "two", 3: "three"}
d[2] = "TWO"
d[4] = "four"
print(d)
print(d.get(5, "not found"), len(d))
Answer:
{1: 'one', 2: 'TWO', 3: 'three', 4: 'four'}
not found 4
Q3: Output Based [2 marks]
Q: Write the output of the following code:
stock = {"pen": 10, "ink": 5, "pad": 8}
x = stock.pop("ink")
y = stock.popitem()
print(x, y)
stock.update({"pen": 12, "clip": 20})
print(stock)
Answer:
5 ('pad', 8)
{'pen': 12, 'clip': 20}
Q4: Output Based [3 marks]
Q: Write the output of the following code:
word = "APPLE"
d = {}
for ch in word:
d[ch] = d.get(ch, 0) + 1
print(d)
for k in sorted(d):
print(k * d[k], end=" ")
print()
print("P" in d, 2 in d, 2 in d.values())
Answer:
{'A': 1, 'P': 2, 'L': 1, 'E': 1}
A E L PP
True False True
Q5: Program [3 marks]
Q: Write a program to input the names and marks of n students into a dictionary and print the names of the students who scored more than 75.
n = int(input("Enter number of students: "))
result = {}
for i in range(n):
name = input("Name: ")
marks = int(input("Marks: "))
result[name] = marks
print("Students scoring above 75:")
for name, marks in result.items():
if marks > 75:
print(name, marks)
โ๏ธ Practice Problems
-
Differentiate between a list and a dictionary (any three points).
-
Write the output of: (a)
dict.fromkeys([1, 2, 3])(b)dict([("a", 1), ("b", 2)])(c){"x": 1, "x": 2}(d)len({}) -
Explain the difference between
del d[key],d.pop(key)andd.popitem()with examples. -
Write a program to input a sentence and print the frequency of each vowel in it using a dictionary.
-
Write a program to create a dictionary with roll numbers as keys and names as values, then delete a record whose roll number is entered by the user (display a message if it doesn't exist).
-
Write a program to input a dictionary of items and prices, and print the items whose price is greater than the average price.
-
Write a program to merge two dictionaries; if a key appears in both, add their values.
-
Write a program to create a dictionary from two lists โ one of country names and one of their capitals โ and then search for the capital of a country entered by the user.
-
Why can a tuple be used as a dictionary key but a list cannot? Give an example of each.
-
Write a program that stores the phone numbers of friends in a dictionary and lets the user (a) add a contact, (b) search for a contact, and (c) display all contacts in alphabetical order of names.