🟢 Beginner · Lesson 14
Dictionaries in Python
What is a Dictionary?
A dictionary stores data as key : value pairs inside curly braces { }. You look up a value using its key — like a real dictionary where the word is the key and the meaning is the value.
Python – dict.py
student = {"name": "Aman", "class": 12, "marks": 95}
print(student["name"])
print(student["marks"])Aman
95
Access, Add, Update
Python – modify.py
student = {"name": "Aman", "marks": 95}
student["class"] = 12 # add a new key
student["marks"] = 98 # update existing
print(student){'name': 'Aman', 'marks': 98, 'class': 12}
- Assigning to a new key adds it.
- Assigning to an existing key updates it.
Dictionary Methods
| Method | Does |
|---|---|
| .keys() | all keys |
| .values() | all values |
| .items() | all key-value pairs |
| .get(k) | value of k (no error if missing) |
| .pop(k) | remove key k |
Program 1: Student Record
Python – record.py
student = {
"name": "Riya",
"roll": 12,
"marks": [88, 92, 79]
}
print("Name :", student["name"])
print("Roll :", student["roll"])
print("Total:", sum(student["marks"]))Name : Riya
Roll : 12
Total: 259
A value can itself be a list — here marks holds three numbers we add with sum().
Program 2: Loop Through a Dictionary
Python – loopdict.py
prices = {"pen": 10, "book": 50, "bag": 400}
for item, price in prices.items():
print(item, "costs", price)pen costs 10
book costs 50
bag costs 400
.items() gives each key and value together, so the loop reads both at once.
Program 3: Count Word Frequency
Python – freq.py
text = "apple banana apple cherry banana apple"
words = text.split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq){'apple': 3, 'banana': 2, 'cherry': 1}
freq.get(w, 0)returns the current count or 0 if the word is new.- We add 1 each time the word appears — a classic counting pattern.
Program 4: Simple Phone Book
Python – phonebook.py
book = {}
book["Aman"] = "98765"
book["Riya"] = "91234"
name = input("Whose number? ")
if name in book:
print(name, ":", book[name])
else:
print("Not found")Whose number? Riya
Riya : 91234
Common Mistakes
- Accessing a missing key with
dict[key]causes a KeyError — use.get(). - Keys must be unique; a repeated key overwrites the old value.
- Lists cannot be keys (keys must be immutable).
Practice Tasks
- Make a dictionary of 3 students and their marks; print the topper.
- Count how many times each character appears in a word.
- Build a small English-Hindi dictionary and look up a word.
- Store product prices and print the total bill.
Summary
- Dictionaries store key:value pairs in
{ }. - Access by key; assigning adds or updates.
- Use
.items()to loop,.get()to avoid KeyError. - Great for records, counting and lookups.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.