LearningPython TutorialDictionaries
CHAPTER 11 · DATA STRUCTURES

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.

English + Hinglish60 min readOnline practice included

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.

dictionary-basic.pyPython
student = {
    "name": "Aman",
    "course": "Python",
    "score": 88
}

print(student)
print(type(student))
Hinglish Explanation

"name", "course" aur "score" keys hain. Har key ke saamne uski value stored hai. Keys unique hoti hain.

Try a dictionary →

Create dictionaries

create.pyPython
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.

keys.pyPython
data = {
    "name": "Kabir",
    101: "student-id",
    (2026, 9): "batch"
}

print(data[101])
Key rule: Duplicate key likhne par later value earlier value ko replace kar deti hai.

Access values with []

access.pyPython
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()

get.pyPython
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

update.pyPython
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

update-method.pyPython
profile = {"name": "Riya", "city": "Lucknow"}
profile.update({"city": "Delhi", "course": "Python"})

print(profile)

Remove items

remove.pyPython
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

membership.pyPython
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()

views.pyPython
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

iterate.pyPython
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

nested.pyPython
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

records.pyPython
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

copying.pyPython
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.

Nested caution: Shallow copy me nested mutable objects ab bhi shared ho sakte hain.

Merge dictionaries

merge.pyPython
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

setdefault.pyPython
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()

fromkeys.pyPython
subjects = ["Python", "DBMS", "Math"]
marks = dict.fromkeys(subjects, 0)
print(marks)
Mutable-default caution: dict.fromkeys(keys, []) me same list object sab keys share kar sakti hain. Beginner code me immutable defaults safer hain.

Dictionary comprehension — preview

dict-comprehension.pyPython
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

frequency.pyPython
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.

Run frequency counter →

Common beginner mistakes

  • Missing key ko [] se access karke unexpected KeyError create 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() aur popitem() ko confuse karna.
  • alias = original ko 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?
  • [] vs get() 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.

  1. Student ke liye name, course, city aur marks keys banao.
  2. marks ko nested dictionary rakho with at least 3 subjects.
  3. Name aur course print karo.
  4. Ek subject ka mark update karo.
  5. New email key add karo.
  6. Optional phone number ko get() se safely read karo.
  7. All keys and values print karo.
  8. items() se full record loop karo.
  9. Marks ka average calculate karo.
  10. Highest subject identify karo using beginner-friendly loop.
  11. Record ki shallow copy banao.
  12. Original aur copy ke behavior ko compare karo.
  13. At least one key membership test use karo.
  14. Clean final summary f-string se print karo.

Open practice starter →