📦 Unit 2 – Strings, Lists, Tuples & Dictionaries · Lesson 24
Dictionaries: Keys, Values & Methods
What is a dictionary?
A dictionary stores data as key : value pairs inside curly brackets { }. Instead of a number index, you look up a value by its key — just like a real dictionary where you find the meaning (value) by the word (key), or a phone book where the name gives the number.
| Key | Value |
|---|---|
| 'name' | 'Meera' |
| 'roll' | 14 |
| 'marks' | 91.5 |
- Keys are unique and must be immutable (str, int, tuple).
- Values can be anything and can repeat.
- Dictionaries are mutable; since Python 3.7 they keep insertion order.
Creating and accessing
Python
student = {'name': 'Meera', 'roll': 14, 'marks': 91.5}
empty = {}
from_pairs = dict([('a', 1), ('b', 2)])
from_kw = dict(city='Pune', pin=411001)
print(student)
print(empty, from_pairs, from_kw)
print(student['name'], student['marks'], len(student)){'name': 'Meera', 'roll': 14, 'marks': 91.5}
{} {'a': 1, 'b': 2} {'city': 'Pune', 'pin': 411001}
Meera 91.5 3
Python
student = {'name': 'Meera', 'roll': 14}
print(student['class'])KeyError: 'class'
Adding, updating and deleting
Python
d = {'name': 'Meera', 'roll': 14}
d['class'] = 'XI-B' # new key -> added
d['roll'] = 15 # existing key -> updated
print(d)
del d['class'] # delete one pair
print(d)
print('roll' in d, 'Meera' in d) # 'in' checks KEYS only{'name': 'Meera', 'roll': 15, 'class': 'XI-B'}
{'name': 'Meera', 'roll': 15}
True False
Traversing a dictionary
Python
price = {'pen': 10, 'book': 60, 'bag': 450}
for item in price: # keys
print(item, end=' ')
print()
for item, cost in price.items(): # key, value pairs
print(f'{item:<5} Rs.{cost}')pen book bag
pen Rs.10
book Rs.60
bag Rs.450
Dictionary methods
Python
d = {'pen': 10, 'book': 60, 'bag': 450}
print(d.keys())
print(d.values())
print(d.items())
print(d.get('book'), d.get('ink'), d.get('ink', 0))
d.update({'ink': 25, 'pen': 12})
print(d)
print(d.pop('bag'), d)
print(d.popitem(), d) # removes the last inserted pair
c = d.copy(); d.clear()
print(c, d)dict_keys(['pen', 'book', 'bag'])
dict_values([10, 60, 450])
dict_items([('pen', 10), ('book', 60), ('bag', 450)])
60 None 0
{'pen': 12, 'book': 60, 'bag': 450, 'ink': 25}
450 {'pen': 12, 'book': 60, 'ink': 25}
('ink', 25) {'pen': 12, 'book': 60}
{'pen': 12, 'book': 60} {}
| Method | Does |
|---|---|
| keys(), values(), items() | Views of keys, values, (key, value) pairs |
| get(k, default) | Value of k, or default/None if missing |
| update(d2) | Add/overwrite pairs from d2 |
| pop(k) | Remove k and return its value |
| popitem() | Remove and return the last inserted pair |
| setdefault(k, v) | Return d[k]; if missing, insert k with v |
| copy(), clear() | Shallow copy / remove all pairs |
| dict.fromkeys(keys, v) | New dictionary with given keys, all = v |
Built-in functions
Python
d = {'b': 2, 'c': 3, 'a': 1}
print(sorted(d), sorted(d.values()))
print(max(d), min(d.values()), sum(d.values()))
print(dict.fromkeys(['x', 'y'], 0))['a', 'b', 'c'] [1, 2, 3]
c 1 6
{'x': 0, 'y': 0}
Solved programs
1. Character frequency
Python
text = 'mississippi'
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
print(freq){'m': 1, 'i': 4, 's': 4, 'p': 2}
2. Student result dictionary
Python
n = int(input('How many students? '))
result = {}
for i in range(n):
name = input('Name: ')
marks = int(input('Marks: '))
result[name] = marks
print(result)
top = max(result, key=result.get)
print('Topper:', top, 'with', result[top])
print('Passed:', [k for k, v in result.items() if v >= 33])How many students? 3
Name: Aditi
Marks: 88
Name: Rohan
Marks: 29
Name: Sana
Marks: 95
{'Aditi': 88, 'Rohan': 29, 'Sana': 95}
Topper: Sana with 95
Passed: ['Aditi', 'Sana']
3. Word count with a star chart
Python
words = 'the cat and the hat and the bat'.split()
count = {}
for w in words:
count[w] = count.get(w, 0) + 1
for w, c in count.items():
print(w, '*' * c)the ***
cat *
and **
hat *
bat *
4. Phone book search
Python
contacts = {'Asha': '98110 22334', 'Vikram': '99887 76655'}
name = input('Search name: ')
print(contacts.get(name, 'Not found'))Search name: Vikram
99887 76655
Nested dictionaries
Python
school = {
'XI-A': {'teacher': 'Mrs. Rao', 'students': 38},
'XI-B': {'teacher': 'Mr. Khan', 'students': 41},
}
print(school['XI-B']['teacher'])
total = 0
for sec, info in school.items():
total += info['students']
print('Total students:', total)Mr. Khan
Total students: 79
List vs dictionary
List
- Ordered items accessed by number index
- marks[0]
- Good for a sequence of similar items
Dictionary
- Values accessed by meaningful key
- marks['Maths']
- Good for records and look-ups; very fast search by key
Summary & practice
- Dictionary = mutable collection of unique key : value pairs in
{ }. d[k] = vadds or updates;del d[k]/pop(k)removes.get()avoids KeyError;items()is best for traversal.- Frequency counting:
d[x] = d.get(x, 0) + 1.
✅ Practice
1) Create a dictionary of 5 states and capitals; print the capital of a state entered by the user. 2) Invert a dictionary (swap keys and values). 3) Predict: d = {1: 'a', 2: 'b'}; d[1] = 'z'; d[3] = 'c'; print(len(d), d).
Answer 3: 3 {1: 'z', 2: 'b', 3: 'c'}
Frequently Asked Questions
Can two keys in a dictionary be the same?
No. Keys must be unique. If you assign a value to an existing key, the old value is replaced.
What can be used as a dictionary key?
Any immutable type: numbers, strings or tuples (containing immutable items). Lists and dictionaries cannot be keys because they are mutable.
What is the difference between d[key] and d.get(key)?
d[key] raises KeyError if the key is missing. d.get(key) returns None (or a default you give, like d.get(key, 0)) instead of an error.
