Python Dictionaries
Dictionary key-value pairs ko store karta hai. Is chapter me creation, access, update, safe lookup, methods, iteration, nesting, copying, merging aur practical record-management patterns step by step samjhenge.
What is a dictionary?
A dictionary is a mutable mapping of unique keys to values. List me position/index se value milti hai; dictionary me meaningful key se value milti hai.
student = {
"name": "Aman",
"course": "Python",
"score": 88
}
print(student)
print(type(student))"name", "course" aur "score" keys hain. Har key ke saamne uski value stored hai. Keys unique hoti hain.
Create dictionaries
empty = {}
profile = {"name": "Riya", "city": "Delhi"}
settings = dict(theme="dark", language="en")
print(empty)
print(profile)
print(settings){} empty dictionary banata hai. Empty set ke liye set() use hota hai — ye difference yaad rakho.
Keys and values
Dictionary keys hashable honi chahiye. Strings, numbers aur suitable tuples common keys hain. Lists dictionary keys nahi ban sakti because list mutable hoti hai.
data = {
"name": "Kabir",
101: "student-id",
(2026, 9): "batch"
}
print(data[101])Access values with []
student = {"name": "Aman", "score": 88}
print(student["name"])
print(student["score"])Missing key ko [] se access karoge to KeyError aata hai.
Safe lookup with get()
student = {"name": "Aman", "score": 88}
print(student.get("name"))
print(student.get("email"))
print(student.get("email", "Not provided"))get() missing key par error ki jagah None ya provided default return kar sakta hai.
Add and update items
student = {"name": "Aman", "score": 88}
student["city"] = "Delhi"
student["score"] = 92
print(student)Existing key assign karne par value update hoti hai; new key assign karne par new item add hota hai.
Update multiple items
profile = {"name": "Riya", "city": "Lucknow"}
profile.update({"city": "Delhi", "course": "Python"})
print(profile)Remove items
student = {"name": "Aman", "score": 88, "city": "Delhi"}
removed = student.pop("city")
print(removed)
last_item = student.popitem()
print(last_item)
student.clear()
print(student)pop(key)key remove karke value return karta hai.popitem()most recently inserted item remove karke key-value tuple return karta hai.del student["key"]direct deletion ke liye use ho sakta hai.clear()dictionary empty karta hai.
Membership checks keys
student = {"name": "Aman", "score": 88}
print("name" in student)
print("Aman" in student)Dictionary par in by default keys check karta hai, values nahi.
keys(), values() and items()
student = {"name": "Aman", "score": 88}
print(student.keys())
print(student.values())
print(student.items())Ye dictionary view objects return karte hain. Views dictionary changes ko reflect kar sakte hain.
Iterate through dictionaries
student = {"name": "Aman", "course": "Python", "score": 88}
for key in student:
print(key, student[key])
for key, value in student.items():
print(f"{key}: {value}")Key aur value dono chahiye ho to items() usually cleanest choice hai.
Insertion order
Modern Python dictionaries insertion order preserve karti hain. Lekin dictionary ka main purpose key-based lookup hai; ordered sequence behavior ke liye list ko replace karna zaroori nahi.
Nested dictionaries
student = {
"name": "Riya",
"marks": {
"python": 92,
"dbms": 85
}
}
print(student["marks"]["python"])Real applications me records ke andar nested dictionaries common hoti hain.
Lists of dictionaries
students = [
{"name": "Aman", "score": 88},
{"name": "Riya", "score": 92},
{"name": "Kabir", "score": 74}
]
for student in students:
print(student["name"], student["score"])Ye pattern API data, database rows aur structured records me bahut common hai.
Copying dictionaries
original = {"name": "Aman", "score": 88}
alias = original
copied = original.copy()
alias["score"] = 95
print(original)
print(copied)alias = original same dictionary ko reference karta hai. copy() shallow copy banata hai.
Merge dictionaries
defaults = {"theme": "light", "language": "en"}
user = {"theme": "dark"}
settings = defaults | user
print(settings)Modern Python me | dictionaries merge kar sakta hai. Same key par right-side dictionary ki value win karti hai.
setdefault() — use with care
profile = {"name": "Aman"}
profile.setdefault("city", "Unknown")
profile.setdefault("name", "Guest")
print(profile)setdefault() key missing ho to default insert karta hai; existing key ko overwrite nahi karta.
fromkeys()
subjects = ["Python", "DBMS", "Math"]
marks = dict.fromkeys(subjects, 0)
print(marks)dict.fromkeys(keys, []) me same list object sab keys share kar sakti hain. Beginner code me immutable defaults safer hain.Dictionary comprehension — preview
squares = {number: number ** 2 for number in range(1, 6)}
print(squares)Dictionary comprehensions ka detailed treatment Chapter 19 me hoga.
When should you use a dictionary?
- Data ko meaningful labels/keys se access karna ho.
- Structured record represent karna ho.
- Fast key lookup chahiye ho.
- Configuration/settings store karni ho.
- Counts/frequencies track karni ho.
Sequential ordered items ke liye list aur unique membership-focused values ke liye set often better choice hai.
Practical pattern — frequency counter
words = ["python", "html", "python", "css", "python", "css"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)get(word, 0) missing key ke liye zero se count start karta hai.
Common beginner mistakes
- Missing key ko
[]se access karke unexpectedKeyErrorcreate karna. - Dictionary membership ko values check samajhna.
- List ko dictionary key banane ki koshish karna.
- Duplicate keys ko separate items samajhna.
dict.get()ka default behavior na samajhna.pop()aurpopitem()ko confuse karna.alias = originalko independent copy samajhna.- Nested dictionaries me shallow-copy sharing ignore karna.
dict.fromkeys()ke mutable default trap ko ignore karna.- Loop ke dauran dictionary size change karna.
- Meaningful structured data ko positional lists me rakhkar readability reduce karna.
Beginner best practices
- Meaningful, consistent keys choose karo.
- Optional key access ke liye
get()consider karo. - Key aur value dono chahiye to
items()use karo. - Nested structures ko excessively deep mat banao.
- Copying behavior samajhkar mutation karo.
- Configuration merges me overwrite order clear rakho.
- Dictionary ko record-like data ke liye use karo; pure sequence ke liye list better ho sakti hai.
Chapter checklist
- Dictionary create aur values access kar sakte ho?
[]vsget()ka difference clear hai?- Items add, update aur remove kar sakte ho?
keys(),values(),items()use kar sakte ho?- Dictionary iterate kar sakte ho?
- Nested dictionaries aur list-of-dictionaries samajh aaye?
- Aliasing vs shallow copy clear hai?
- Frequency-counter pattern bana sakte ho?
Practice Task — Student Record Manager
BrounStack Playground me dictionary-based student record program banao.
- Student ke liye
name,course,cityaurmarkskeys banao. marksko nested dictionary rakho with at least 3 subjects.- Name aur course print karo.
- Ek subject ka mark update karo.
- New
emailkey add karo. - Optional phone number ko
get()se safely read karo. - All keys and values print karo.
items()se full record loop karo.- Marks ka average calculate karo.
- Highest subject identify karo using beginner-friendly loop.
- Record ki shallow copy banao.
- Original aur copy ke behavior ko compare karo.
- At least one key membership test use karo.
- Clean final summary f-string se print karo.