In a list, you find an item by its position β marks[3]. But what if you want Riya's marks and you don't know her position? π€ You'd love to just ask for marks["Riya"]! That's exactly what a dictionary does. π This chapter answers the BIG questions: What is a keyβvalue pair? How do we create a dictionary, look up a value, add, change and delete items? How do we loop through a dictionary? And which methods β keys(), values(), items(), get(), update() β make life easy? Let's open the dictionary! π
The most tested topics are creating and updating a dictionary, d[key] vs d.get(key), keys(), values(), items(), update(), del vs pop() vs clear(), and programs like counting frequencies and storing student records. Remember one golden rule: keys are unique β everything else follows from it!
7.1 π Introduction β What is a Dictionary?
A dictionary is a collection of key : value pairs, written inside curly brackets { }. Each key is linked to a value, and we use the key to get the value.
student = {"name": "Riya", "class": 11, "marks": 92}
print(student)
print(student["name"])
print(student["marks"])
Output:
{'name': 'Riya', 'class': 11, 'marks': 92}
Riya
92
student = { "name" : "Riya" , "class" : 11 , "marks" : 92 }
ββββββ ββββββ βββββββ ββ βββββββ ββ
key value key value key value
βββββ pair βββββ βββ pair βββ βββ pair βββ
Analogy: A dictionary is exactly like a real dictionary π. You look up a word (key) to find its meaning (value). You don't search by page number β you search by the word itself!
More everyday examples of keyβvalue pairs:
Phone Contacts
Name β Phone number
Name is the keyReport Card
Subject β Marks
Subject is the keyPrice List
Item β Price
Item is the keyRoll Register
Roll number β Student name
Roll no. is the key7.1.1 Features of a Dictionary β
Keys are Unique
The same key cannot appear twice β a repeated key keeps only the LAST value
No duplicate keysKeys are Immutable
Keys must be of an unchangeable type β numbers, strings or tuples. A list can't be a key
intstrtupleValues can be Anything
Values can be of any type and CAN repeat
Any typeMutable
You can add, change and delete pairs after creating it
ChangeableAccessed by Key
Items are reached by key, not by index number
No indexingd = {"a": 1, "b": 2, "a": 99}
print(d)
Output:
{'a': 99, 'b': 2}
{[1, 2]: "x"} gives TypeError: unhashable type: 'list', because lists are mutable. Use a tuple (1, 2) instead.
Every person has a unique Aadhaar number that never changes. Keys too must be unique and unchangeable (immutable). The values (your address, phoneβ¦) can change and can even be the same for two people!
7.2 π οΈ Creating a Dictionary
# 1. Empty dictionary
d1 = {}
d2 = dict()
# 2. With pairs inside { }
price = {"pen": 10, "notebook": 45, "eraser": 5}
# 3. Using dict() with keyword arguments
city = dict(Delhi="DL", Mumbai="MH", Kolkata="WB")
# 4. Using dict() with a list of pairs
roll = dict([(1, "Aman"), (2, "Zoya")])
print(d1, d2)
print(price)
print(city)
print(roll)
Output:
{} {}
{'pen': 10, 'notebook': 45, 'eraser': 5}
{'Delhi': 'DL', 'Mumbai': 'MH', 'Kolkata': 'WB'}
{1: 'Aman', 2: 'Zoya'}
Code Example: input_dict.py β Creating a Dictionary from User Input
marks = {}
n = int(input("How many students? "))
for i in range(n):
name = input("Enter name: ")
m = int(input("Enter marks: "))
marks[name] = m
print(marks)
Sample run (the user types 2, Riya, 92, Aman and 85):
How many students? 2
Enter name: Riya
Enter marks: 92
Enter name: Aman
Enter marks: 85
{'Riya': 92, 'Aman': 85}
7.3 π Accessing Values
We use d[key] to get the value of a key.
price = {"pen": 10, "notebook": 45, "eraser": 5}
print(price["notebook"])
print("pen" in price)
print(10 in price)
print("pencil" not in price)
Output:
45
True
False
True
in checks KEYS, not values!10 in price is False even though 10 is a value, because in looks only at the keys. To check a value, use 10 in price.values().
price["pencil"] gives KeyError: 'pencil'. Use get() (below) or check with in first.
7.3.1 The Safe Way β get() π‘οΈ
d.get(key) returns the value if the key exists, and None (or a default value you give) if it doesn't β no error!
price = {"pen": 10, "notebook": 45}
print(price.get("pen"))
print(price.get("pencil"))
print(price.get("pencil", "Not available"))
Output:
10
None
Not available
d[key] |
d.get(key) |
|---|---|
| Gives KeyError if the key is missing | Gives None (or a default) if the key is missing |
| Can also be used to add or change a value | Only reads a value |
Analogy:
d[key]is like asking a strict librarian for a book β if it's not there, she scolds you (KeyError)! πd.get(key)is a polite librarian who just says "Sorry, not available" π.
7.4 βοΈ Adding, Changing and Deleting Items
graph TD
Q{"π Does the key\nalready exist?"}
CH["βοΈ Value is CHANGED\n(updated)"]
AD["β New pair is ADDED"]
Q -->|"Yes"| CH
Q -->|"No"| AD
style CH fill:#FF9800,color:#fff
style AD fill:#4CAF50,color:#fff
The same statement d[key] = value both adds and changes:
marks = {"Maths": 80, "Science": 75}
marks["Science"] = 90 # key exists β value changed
marks["English"] = 85 # new key β pair added
print(marks)
Output:
{'Maths': 80, 'Science': 90, 'English': 85}
7.4.1 update() β Adding Many Pairs at Once π
d.update(d2) adds all pairs of d2 into d. If a key already exists, its value is replaced.
marks = {"Maths": 80, "Science": 90}
marks.update({"Science": 95, "Hindi": 70})
print(marks)
Output:
{'Maths': 80, 'Science': 95, 'Hindi': 70}
7.4.2 Deleting Items ποΈ
| Way | What it does | Returns |
|---|---|---|
del d[key] |
Deletes the pair with that key | Nothing |
d.pop(key) |
Deletes the pair and gives back its value | The value |
d.popitem() |
Deletes the last added pair | The pair as a tuple |
d.clear() |
Deletes all pairs β {} remains |
Nothing |
del d |
Deletes the whole dictionary β the name is gone | Nothing |
stock = {"apple": 50, "mango": 30, "kiwi": 12, "grape": 40}
del stock["kiwi"]
print(stock)
x = stock.pop("mango")
print(x, stock)
print(stock.popitem(), stock)
stock.clear()
print(stock)
Output:
{'apple': 50, 'mango': 30, 'grape': 40}
30 {'apple': 50, 'grape': 40}
('grape', 40) {'apple': 50}
{}
clear() vs del d β not the same!After d.clear(), d still exists as an empty dictionary {}. After del d, d is gone β print(d) gives a NameError.
"What is the difference between del d[key] and d.pop(key)?" β 2 marks
Answer: Both remove the pair with the given key. del d[key] is a statement and returns nothing, while d.pop(key) is a method that removes the pair and returns its value, which can be stored in a variable. Both give a KeyError if the key is missing (unless a default is given to pop()).
7.5 πΆ Traversing a Dictionary
A for loop over a dictionary goes through its keys. We can then use each key to get its value.
marks = {"Maths": 80, "Science": 95, "Hindi": 70}
for sub in marks:
print(sub, "β", marks[sub])
Output:
Maths β 80
Science β 95
Hindi β 70
7.5.1 keys(), values() and items() ποΈ
marks = {"Maths": 80, "Science": 95, "Hindi": 70}
print(marks.keys())
print(marks.values())
print(marks.items())
print(list(marks.keys()))
Output:
dict_keys(['Maths', 'Science', 'Hindi'])
dict_values([80, 95, 70])
dict_items([('Maths', 80), ('Science', 95), ('Hindi', 70)])
['Maths', 'Science', 'Hindi']
keys()
Gives all the KEYS
Maths Science Hindivalues()
Gives all the VALUES
80 95 70items()
Gives all the PAIRS as tuples
Key and value togetherLooping with items() β get the key AND the value together:
marks = {"Maths": 80, "Science": 95, "Hindi": 70}
for sub, m in marks.items():
print(sub, ":", m)
Output:
Maths : 80
Science : 95
Hindi : 70
Analogy:
keys()gives you just the names on the lockers,values()gives you just what's inside, anditems()gives you both β the label with the contents! π
7.6 π§° Functions and Methods at a Glance
marks = {"Maths": 80, "Science": 95, "Hindi": 70}
print(len(marks))
print(max(marks.values()), min(marks.values()), sum(marks.values()))
print(sorted(marks))
print(max(marks))
Output:
3
95 70 245
['Hindi', 'Maths', 'Science']
Science
max(d), min(d), sorted(d) work on the KEYS!max(marks) gives Science (alphabetically last key), NOT the highest marks. For the highest marks, use max(marks.values()).
| Name | Use | Example (d = {"a": 1, "b": 2}) |
|---|---|---|
len(d) |
Number of pairs | 2 |
dict() |
Creates a dictionary | dict(a=1) β {'a': 1} |
d.keys() |
All keys | dict_keys(['a', 'b']) |
d.values() |
All values | dict_values([1, 2]) |
d.items() |
All pairs as tuples | dict_items([('a', 1), ('b', 2)]) |
d.get(k, default) |
Value of k, or default if missing | d.get("z", 0) β 0 |
d.update(d2) |
Add / replace pairs from d2 | |
d.pop(k) |
Remove k and return its value | d.pop("a") β 1 |
d.popitem() |
Remove and return the last pair | ('b', 2) |
d.clear() |
Remove all pairs | {} |
del d[k] |
Remove the pair with key k | |
sorted(d) |
Sorted list of keys | ['a', 'b'] |
7.7 βοΈ List vs Dictionary
| List | Dictionary |
|---|---|
Written in square brackets [ ] |
Written in curly brackets { } |
| Stores single values | Stores key : value pairs |
| Items reached by index (0, 1, 2β¦) | Values reached by key |
| Duplicate items allowed | Keys must be unique (values can repeat) |
e.g. [85, 92, 78] |
e.g. {"Riya": 85, "Aman": 92} |
"How is a dictionary different from a list?" β 2 marks
Answer: A list is an ordered collection of values written in [ ], whose items are accessed by their index. A dictionary is a collection of key : value pairs written in { }, whose values are accessed by their keys; keys must be unique and immutable.
7.8 π» Important Programs on Dictionaries
Code Example: char_frequency.py β Count Each Character
text = "banana"
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
Output:
{'b': 1, 'a': 3, 'n': 2}
Dry run for "banana":
| ch | Already a key? | freq after this step |
|---|---|---|
| b | No β add | {'b': 1} |
| a | No β add | {'b': 1, 'a': 1} |
| n | No β add | {'b': 1, 'a': 1, 'n': 1} |
| a | Yes β +1 | {'b': 1, 'a': 2, 'n': 1} |
| n | Yes β +1 | {'b': 1, 'a': 2, 'n': 2} |
| a | Yes β +1 | {'b': 1, 'a': 3, 'n': 2} |
The whole ifβelse can be written in one line: freq[ch] = freq.get(ch, 0) + 1. If ch is new, get() gives 0, so it becomes 1!
Code Example: word_count.py β Count Words in a Sentence
sentence = "the cat and the dog and the bird"
count = {}
for w in sentence.split():
count[w] = count.get(w, 0) + 1
print(count)
Output:
{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
Code Example: topper.py β Find the Topper
marks = {"Riya": 92, "Aman": 85, "Zoya": 97, "Kabir": 78}
topper = ""
high = -1
for name, m in marks.items():
if m > high:
high = m
topper = name
print("Topper:", topper, "with", high, "marks")
Output:
Topper: Zoya with 97 marks
Code Example: passed.py β Students Who Scored 80 or More
marks = {"Riya": 92, "Aman": 65, "Zoya": 97, "Kabir": 78}
for name in marks:
if marks[name] >= 80:
print(name)
Output:
Riya
Zoya
Code Example: phonebook.py β Search a Contact
phone = {"Mom": "98300 11111", "Dad": "98300 22222", "Riya": "98300 33333"}
name = input("Whose number? ")
print(phone.get(name, "Contact not found"))
Sample run (the user types Riya):
Whose number? Riya
98300 33333
"Write a program to store the names of items and their prices in a dictionary, then increase the price of every item by 10%." β 3 marks Answer:
price = {"pen": 10, "bag": 500, "bottle": 150}
for item in price:
price[item] = price[item] * 1.1
print(price)
Output: {'pen': 11.0, 'bag': 550.0, 'bottle': 165.0}
β οΈ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
d[0] to get the first item |
Dictionaries have no index | Access by key: d["name"] |
| Using a list as a key | Keys must be immutable | Use a string, number or tuple |
| Expecting two values for a repeated key | Keys are unique | The last value replaces the earlier one |
10 in d to check a value |
in checks only keys |
Use 10 in d.values() |
d["x"] for a missing key |
Gives KeyError | Use d.get("x") or check "x" in d |
max(d) for the highest value |
Works on keys | Use max(d.values()) |
d.clear() deletes the dictionary |
It only empties it | del d deletes the name itself |
d.update("k", 5) |
update() takes a dictionary | d.update({"k": 5}) |
for k, v in d: |
Looping over d gives only keys | Use for k, v in d.items(): |
Writing {"a" = 1} |
Pairs use a colon | Write {"a": 1} |
π Quick Revision β Exam Ready!
- Dictionary β collection of key : value pairs in
{ } - Keys β unique and immutable (str, int, tuple); values β any type, can repeat
- Mutable β pairs can be added, changed and deleted
- Create β
{},dict(),dict(a=1),dict([(k, v), β¦]), ord[k] = vin a loop - Access β
d[key](KeyError if missing) ord.get(key, default)(no error) - Add / change β
d[key] = value(adds if new, changes if existing);d.update(d2) - Delete β
del d[key],d.pop(key)(returns value),d.popitem()(last pair),d.clear()(empties),del d(removes the name) inβ checks keys only- Traverse β
for k in d:gives keys;for k, v in d.items():gives both - keys(), values(), items() β all keys, all values, all pairs
- len(d) β number of pairs;
max/min/sorted(d)β work on keys - Frequency count β
freq[x] = freq.get(x, 0) + 1
π― Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) Which brackets are used to create a dictionary?
Answer: Curly brackets { }
b) Can two keys in a dictionary be the same? Answer: No β keys must be unique
c) Which method returns all the keys of a dictionary?
Answer: keys()
d) What does d.get("x") return if "x" is not a key?
Answer: None
e) Which method removes a key and returns its value?
Answer: pop()
Q2: Output Based [2 marks]
d = {1: "one", 2: "two", 3: "three"}
d[2] = "TWO"
d[4] = "four"
print(d)
print(len(d), 3 in d, "one" in d)
Answer:
{1: 'one', 2: 'TWO', 3: 'three', 4: 'four'}
4 True False
Q3: Output Based [3 marks]
fees = {"Riya": 5000, "Aman": 4500}
fees.update({"Zoya": 5200, "Aman": 4800})
print(fees)
x = fees.pop("Riya")
print(x, list(fees.keys()))
print(fees.get("Riya", 0), sum(fees.values()))
Answer:
{'Riya': 5000, 'Aman': 4800, 'Zoya': 5200}
5000 ['Aman', 'Zoya']
0 10000
Q4: Short Answer [2 marks]
What is the difference between d.clear() and del d?
Answer: d.clear() removes all the pairs, but the dictionary still exists as an empty dictionary {}. del d deletes the dictionary itself, so using d afterwards gives a NameError.
Q5: Program [3 marks]
Write a program to input a string and print how many times each vowel appears in it.
Answer:
text = input("Enter a string: ")
count = {}
for ch in text.lower():
if ch in "aeiou":
count[ch] = count.get(ch, 0) + 1
print(count)
Sample run (the user types Education is Important):
Enter a string: Education is Important
{'e': 1, 'u': 1, 'a': 2, 'i': 3, 'o': 2}
βοΈ Practice Problems
- Create a dictionary of 5 states and their capitals. Print the capital of any one state.
- Why can a tuple be a key but a list cannot?
- Write the output:
d = {"x": 1, "y": 2, "x": 3}followed byprint(d, len(d)) - What is the difference between
d["k"]andd.get("k")when"k"is not a key? - Write a program to input the names and marks of N students into a dictionary and print the names of students who scored more than 75.
- Write a program to count how many times each number appears in the list
[2, 3, 2, 5, 3, 2]. - Given
price = {"tea": 20, "coffee": 35, "juice": 50}, write code to (a) add"lassi": 40(b) change coffee to 40 (c) delete tea. - Write a program to print the items of a dictionary whose value is an even number.
- Write a program to find the key with the lowest value in a dictionary.
- Write a program that swaps keys and values, e.g.
{"a": 1, "b": 2}β{1: "a", 2: "b"}. - Write a program to create a dictionary where the keys are numbers 1 to 5 and the values are their squares.
- Write the output:
d = {"b": 2, "a": 1}followed byprint(sorted(d), max(d), max(d.values()))