Creating a dictionary and accessing by key
D = {'Riya': 91, 'Aman': 85, 'Dev': 78}, E = {}, dict(a=1, b=2).
Access: D['Aman'] → 85. A key that is not there gives KeyError. D.get('Zoya') returns None instead, and D.get('Zoya', 0) returns 0.
Keys must be unique and immutable (int, str, tuple); a list cannot be a key. Membership 'Riya' in D checks keys, not values.
Adding and changing items
D['Zoya'] = 88 # new key → pair added
D['Riya'] = 95 # old key → value changed
del D['Dev'] # remove a pair
D.update({'Aman': 90, 'Ira': 70})Dictionaries are mutable, and from Python 3.7 they keep the order in which keys were added.
Traversing a dictionary
for k in D:
print(k, D[k])
for k, v in D.items():
print(k, '→', v)
Dictionary functions and methods
| Method | What it does |
|---|---|
| len(D) | number of pairs |
| D.keys(), D.values(), D.items() | all keys / values / (key, value) pairs |
| D.get(k, default) | value of k, or default (no error) |
| D.update(D2) | adds or changes pairs from D2 |
| D.pop(k) | removes k and returns its value |
| D.popitem() | removes and returns the last added pair |
| D.setdefault(k, v) | returns D[k]; if k is missing, adds it with v |
| dict.fromkeys(keys, v) | new dict with the given keys all set to v |
| D.copy(), D.clear() | shallow copy / remove all pairs |
| sorted(D), max(D), min(D) | work on the keys |
Program: count each character in a string
s = input('Enter text: ')
d = {}
for ch in s:
if ch in d:
d[ch] += 1
else:
d[ch] = 1
print(d)
# 'banana' → {'b': 1, 'a': 3, 'n': 2}Shorter: d[ch] = d.get(ch, 0) + 1. The same idea counts words: loop over s.split().
Program: student marks dictionary
n = int(input('How many students? '))
marks = {}
for i in range(n):
name = input('Name: ')
marks[name] = int(input('Marks: '))
for name, m in marks.items():
if m > 75:
print(name)
Key formulas and definitions
- D = {key: value, …}; D[key] to read
- Missing key: D[k] → KeyError; D.get(k) → None
- D[k] = v adds or changes
- Keys: unique and immutable
- count: d[ch] = d.get(ch, 0) + 1
Worked examples
1. D = {'a': 1, 'b': 2}. What are D['b'], len(D), 'a' in D, 1 in D?
2; 2; True; False (in checks keys, and 1 is a value).
2. Output? D = {'x': 5}; D['y'] = 7; D['x'] = 9; print(D)
{'x': 9, 'y': 7}
3. Output? D = {'Riya': 91, 'Aman': 85}; print(D.get('Dev', 'absent'), D.pop('Aman'), D)
absent 85 {'Riya': 91}
4. Count characters in 'hello'.
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
5. Count words in 'to be or not to be'.
d = {} for w in 'to be or not to be'.split(): d[w] = d.get(w, 0) + 1 # {'to': 2, 'be': 2, 'or': 1, 'not': 1}
6. Find the student with the highest marks in {'Riya': 91, 'Aman': 85, 'Dev': 97}.
best = max(D, key=D.get) → 'Dev'. Or loop: keep the name whose value is largest.
Common mistakes
- Reading a missing key with D[k] and getting KeyError. Use get() or check with in first.
- Using a list as a key. Keys must be immutable.
- Thinking 'in' checks values. It checks keys; use v in D.values() for values.
- Expecting two equal keys to be kept. A repeated key overwrites the earlier value.