🐍 Unit 2 – Python Programming · Lesson 09
Python में Dictionaries
Dictionary क्या है?
Dictionary curly brackets में data को key : value pairs के रूप में रखती है। हर key unique और immutable होनी चाहिए; values कुछ भी हो सकती हैं। List बताती है "position 2 पर क्या है?", dictionary बताती है "pen की price क्या है?"।
| key | value |
|---|---|
| 'title' | 'Wings of Fire' |
| 'author' | 'A. P. J. Abdul Kalam' |
| 'price' | 299 |
बनाना और access करना
Python
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)Wings of Fire
299 None unknown
3 True
न मौजूद key के लिए d[key] से KeyError आती है; get() सुरक्षित तरीका है।
जोड़ना, बदलना, हटाना
Python
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){'pen': 100, 'pencil': 80, 'eraser': 45}
{'pen': 100, 'eraser': 45}
45 {'pen': 100}
Traverse करना
Python
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}')Delhi, Mumbai, Kolkata, Chennai,
Delhi ●●●●●●●●●●● 33
Mumbai ●●●●●●● 22
Kolkata ●●●●● 15
Chennai ●●●● 12
Dictionary methods
Python
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)['Maths', 'Physics', 'IP']
[88, 76, 95]
[('Maths', 88), ('Physics', 76), ('IP', 95)]
{'Maths': 90, 'Physics': 76, 'IP': 95, 'English': 81}
['English', 'IP', 'Maths', 'Physics'] 95
('English', 81) {'Maths': 90, 'Physics': 76, 'IP': 95}
| Method | काम |
|---|---|
| keys(), values(), items() | सभी keys / values / pairs |
| get(k, default) | सुरक्षित access |
| update(other) | दूसरी dictionary मिलाना (same keys overwrite) |
| pop(k), popitem() | एक key / आख़िरी pair हटाना |
| copy(), clear() | Copy / ख़ाली करना |
| len(), sorted(), max(), min(), sum(d.values()) | Built-in helpers |
Programs
1. Votes गिनना
Python
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'){'A': 4, 'B': 2, 'C': 1}
Winner: A with 4 votes
2. Employee salary dictionary
Python
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')Number of employees: 3
Name: Ravi
Salary: 38000
Name: Meena
Salary: 52000
Name: Joseph
Salary: 41000
{'Ravi': 38000, 'Meena': 52000, 'Joseph': 41000}
Total salary bill: 131000
Meena earns more than 40000
Joseph earns more than 40000
3. Dictionary comprehension और zip()
Python
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]))){'apple': 5, 'mango': 5, 'kiwi': 4}
{'a': 1, 'b': 2, 'c': 3}
Nested dictionaries
Value ख़ुद dictionary या list हो सकती है — असली records (websites और apps का JSON data) ऐसे ही दिखते हैं।
Python
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))101 Asha 84.33
102 Dev 65.33
सारांश और practice
- Dictionary = { } में values से जुड़ी unique keys; mutable।
- d[k] या d.get(k) से access; d[k] = v से जोड़ना/बदलना; del, pop से हटाना।
- items() से traverse; methods keys, values, update, popitem।
- गिनती pattern: d[x] = d.get(x, 0) + 1।
✅ Practice
1) एक घर के 6 महीनों की बिजली units store करके सबसे ज़्यादा use वाला महीना print करें। 2) Sentence में हर word कितनी बार आया, गिनें। 3) 5 products और उनकी prices की dictionary बनाकर ₹100 से महँगे products print करें।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
Data handling में dictionary useful क्यों है?
असली data अक्सर labelled values में आता है — student का नाम, roll और marks, या product का code और price। Dictionary हर value को उसके label (key) के साथ रखती है, इसलिए पढ़ना आसान और ढूँढना तेज़ है।
क्या dictionary keys case-sensitive हैं?
हाँ। "Maths" और "maths" अलग keys हैं।
items() क्या return करता है?
(key, value) pairs का view, जो for k, v in d.items() जैसे loop के लिए बढ़िया है।
