Dictionaries in Python
What is a dictionary?
A dictionary stores data as key : value pairs in curly brackets. Each key must be unique and immutable; values can be anything. Where a list answers "what is at position 2?", a dictionary answers "what is the price of a pen?".
| key | value |
|---|---|
| 'title' | 'Wings of Fire' |
| 'author' | 'A. P. J. Abdul Kalam' |
| 'price' | 299 |
Creating and accessing
book = {'title': 'Wings of Fire', 'author': 'A. P. J. Abdul Kalam', 'price': 299}
print(book['title'])
print(book.get('price'), book.get('pages'), book.get('pages', 'unknown'))
print(len(book), 'author' in book)Using d[key] for a missing key raises KeyError; get() is the safe way.
Adding, modifying, deleting
stock = {'pen': 120, 'pencil': 80}
stock['eraser'] = 45 # add
stock['pen'] = 100 # modify
print(stock)
del stock['pencil'] # delete
print(stock)
print(stock.pop('eraser'), stock)Traversing
population = {'Delhi': 33, 'Mumbai': 22, 'Kolkata': 15, 'Chennai': 12} # lakh, approx.
for city in population:
print(city, end=', ')
print()
for city, p in population.items():
print(f'{city:<8}{"●" * (p // 3)} {p}')Dictionary methods
marks = {'Maths': 88, 'Physics': 76, 'IP': 95}
print(list(marks.keys()))
print(list(marks.values()))
print(list(marks.items()))
marks.update({'English': 81, 'Maths': 90})
print(marks)
print(sorted(marks), max(marks.values()))
print(marks.popitem(), marks)| Method | Purpose |
|---|---|
| keys(), values(), items() | All keys / values / pairs |
| get(k, default) | Safe access |
| update(other) | Merge another dictionary (overwrites same keys) |
| pop(k), popitem() | Remove a key / the last pair |
| copy(), clear() | Copy / empty |
| len(), sorted(), max(), min(), sum(d.values()) | Built-in helpers |
Programs
1. Counting votes
votes = ['A', 'B', 'A', 'C', 'A', 'B', 'A']
result = {}
for v in votes:
result[v] = result.get(v, 0) + 1
print(result)
winner = max(result, key=result.get)
print('Winner:', winner, 'with', result[winner], 'votes')2. Employee salary dictionary
n = int(input('Number of employees: '))
salary = {}
for i in range(n):
name = input('Name: ')
salary[name] = int(input('Salary: '))
print(salary)
print('Total salary bill:', sum(salary.values()))
for name, s in salary.items():
if s > 40000:
print(name, 'earns more than 40000')3. Dictionary comprehension and zip()
fruits = ['apple', 'mango', 'kiwi']
lengths = {f: len(f) for f in fruits} # dictionary comprehension
print(lengths)
print(dict(zip(['a', 'b', 'c'], [1, 2, 3])))Nested dictionaries
A value can itself be a dictionary or list — this is how real records (JSON data from websites and apps) look.
students = {
101: {'name': 'Asha', 'marks': [78, 85, 90]},
102: {'name': 'Dev', 'marks': [66, 72, 58]},
}
for roll, info in students.items():
avg = sum(info['marks']) / len(info['marks'])
print(roll, info['name'], round(avg, 2))Summary & practice
- Dictionary = unique keys mapped to values in { }; mutable.
- Access with d[k] or d.get(k); add/modify with d[k] = v; delete with del, pop.
- Traverse with items(); methods keys, values, update, popitem.
- Counting pattern: d[x] = d.get(x, 0) + 1.
1) Store the monthly electricity units of a house for 6 months and print the month with the highest use. 2) Count how many times each word appears in a sentence. 3) Create a dictionary of 5 products and their prices, and print products costing more than ₹100.
