🟢 Beginner  ·  Lesson 14

Dictionaries in Python

Python Dictionaries

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

MethodDoes
.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

  1. Make a dictionary of 3 students and their marks; print the topper.
  2. Count how many times each character appears in a word.
  3. Build a small English-Hindi dictionary and look up a word.
  4. 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.

Dictionary क्या है?

Dictionary data को key : value pairs के रूप में curly braces { } में रखती है। आप key से value ढूंढते हैं — असली dictionary की तरह जहाँ शब्द key है और अर्थ 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        # नई key जोड़ें
student["marks"] = 98        # मौजूदा update करें
print(student)
{'name': 'Aman', 'marks': 98, 'class': 12}
  • नई key को assign करने पर वह जुड़ जाती है।
  • मौजूदा key को assign करने पर वह update होती है।

Dictionary Methods

Methodक्या करता है
.keys()सभी keys
.values()सभी values
.items()सभी key-value pairs
.get(k)k की value (missing पर error नहीं)
.pop(k)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

Value खुद एक list हो सकती है — यहाँ marks में तीन numbers हैं जिन्हें sum() से जोड़ते हैं।

Program 2: Dictionary पर Loop

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() हर key और value एक साथ देता है, इसलिए loop दोनों एक बार में पढ़ता है।

Program 3: 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) मौजूदा count या नया word होने पर 0 लौटाता है।
  • हर बार word आने पर 1 जोड़ते हैं — classic counting pattern।

Program 4: छोटा 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

सामान्य गलतियाँ

  • missing key को dict[key] से access करने पर KeyError — .get() use करें।
  • Keys unique होनी चाहिए; दोहराई key पुरानी value overwrite करती है।
  • Lists keys नहीं हो सकतीं (keys immutable होनी चाहिए)।

Practice Tasks

  1. 3 students और उनके marks की dictionary बनाकर topper print करें।
  2. किसी word में हर character कितनी बार आता है, गिनें।
  3. छोटी English-Hindi dictionary बनाकर एक word ढूंढें।
  4. Product prices store करके कुल bill print करें।

सारांश

  • Dictionaries { } में key:value pairs रखती हैं।
  • Key से access; assign करने पर जुड़ता या update होता है।
  • Loop के लिए .items(), KeyError से बचने के लिए .get()
  • Records, counting और lookups के लिए बढ़िया।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

WhatsApp