📦 Unit 2 – Strings, Lists, Tuples और Dictionaries · Lesson 24
Dictionaries: Keys, Values और Methods
Dictionary क्या है?
Dictionary curly brackets { } के अंदर data को key : value pairs के रूप में रखती है। Number index की जगह value उसकी key से ढूँढी जाती है — बिल्कुल असली dictionary जैसे जहाँ शब्द (key) से अर्थ (value) मिलता है, या phone book जहाँ नाम से number।
| Key | Value |
|---|---|
| 'name' | 'Meera' |
| 'roll' | 14 |
| 'marks' | 91.5 |
- Keys unique और immutable (str, int, tuple) होनी चाहिए।
- Values कुछ भी हो सकती हैं और दोहराई जा सकती हैं।
- Dictionaries mutable हैं; Python 3.7 से insertion order बना रहता है।
बनाना और access करना
Python
student = {'name': 'Meera', 'roll': 14, 'marks': 91.5}
empty = {}
from_pairs = dict([('a', 1), ('b', 2)])
from_kw = dict(city='Pune', pin=411001)
print(student)
print(empty, from_pairs, from_kw)
print(student['name'], student['marks'], len(student)){'name': 'Meera', 'roll': 14, 'marks': 91.5}
{} {'a': 1, 'b': 2} {'city': 'Pune', 'pin': 411001}
Meera 91.5 3
Python
student = {'name': 'Meera', 'roll': 14}
print(student['class'])KeyError: 'class'
जोड़ना, update और delete करना
Python
d = {'name': 'Meera', 'roll': 14}
d['class'] = 'XI-B' # new key -> added
d['roll'] = 15 # existing key -> updated
print(d)
del d['class'] # delete one pair
print(d)
print('roll' in d, 'Meera' in d) # 'in' checks KEYS only{'name': 'Meera', 'roll': 15, 'class': 'XI-B'}
{'name': 'Meera', 'roll': 15}
True False
Dictionary traverse करना
Python
price = {'pen': 10, 'book': 60, 'bag': 450}
for item in price: # keys
print(item, end=' ')
print()
for item, cost in price.items(): # key, value pairs
print(f'{item:<5} Rs.{cost}')pen book bag
pen Rs.10
book Rs.60
bag Rs.450
Dictionary methods
Python
d = {'pen': 10, 'book': 60, 'bag': 450}
print(d.keys())
print(d.values())
print(d.items())
print(d.get('book'), d.get('ink'), d.get('ink', 0))
d.update({'ink': 25, 'pen': 12})
print(d)
print(d.pop('bag'), d)
print(d.popitem(), d) # removes the last inserted pair
c = d.copy(); d.clear()
print(c, d)dict_keys(['pen', 'book', 'bag'])
dict_values([10, 60, 450])
dict_items([('pen', 10), ('book', 60), ('bag', 450)])
60 None 0
{'pen': 12, 'book': 60, 'bag': 450, 'ink': 25}
450 {'pen': 12, 'book': 60, 'ink': 25}
('ink', 25) {'pen': 12, 'book': 60}
{'pen': 12, 'book': 60} {}
| Method | क्या करता है |
|---|---|
| keys(), values(), items() | Keys, values, (key, value) pairs के views |
| get(k, default) | k की value, न हो तो default/None |
| update(d2) | d2 के pairs जोड़ना/overwrite |
| pop(k) | k हटाकर उसकी value return |
| popitem() | आख़िरी डाला pair हटाकर return |
| setdefault(k, v) | d[k] return; न हो तो k को v के साथ डालो |
| copy(), clear() | Shallow copy / सारे pairs हटाओ |
| dict.fromkeys(keys, v) | दी गई keys वाली नई dictionary, सबकी value v |
Built-in functions
Python
d = {'b': 2, 'c': 3, 'a': 1}
print(sorted(d), sorted(d.values()))
print(max(d), min(d.values()), sum(d.values()))
print(dict.fromkeys(['x', 'y'], 0))['a', 'b', 'c'] [1, 2, 3]
c 1 6
{'x': 0, 'y': 0}
Solved programs
1. Character frequency
Python
text = 'mississippi'
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
print(freq){'m': 1, 'i': 4, 's': 4, 'p': 2}
2. Student result dictionary
Python
n = int(input('How many students? '))
result = {}
for i in range(n):
name = input('Name: ')
marks = int(input('Marks: '))
result[name] = marks
print(result)
top = max(result, key=result.get)
print('Topper:', top, 'with', result[top])
print('Passed:', [k for k, v in result.items() if v >= 33])How many students? 3
Name: Aditi
Marks: 88
Name: Rohan
Marks: 29
Name: Sana
Marks: 95
{'Aditi': 88, 'Rohan': 29, 'Sana': 95}
Topper: Sana with 95
Passed: ['Aditi', 'Sana']
3. Star chart के साथ word count
Python
words = 'the cat and the hat and the bat'.split()
count = {}
for w in words:
count[w] = count.get(w, 0) + 1
for w, c in count.items():
print(w, '*' * c)the ***
cat *
and **
hat *
bat *
4. Phone book search
Python
contacts = {'Asha': '98110 22334', 'Vikram': '99887 76655'}
name = input('Search name: ')
print(contacts.get(name, 'Not found'))Search name: Vikram
99887 76655
Nested dictionaries
Python
school = {
'XI-A': {'teacher': 'Mrs. Rao', 'students': 38},
'XI-B': {'teacher': 'Mr. Khan', 'students': 41},
}
print(school['XI-B']['teacher'])
total = 0
for sec, info in school.items():
total += info['students']
print('Total students:', total)Mr. Khan
Total students: 79
List vs dictionary
List
- Number index से access होने वाले ordered items
- marks[0]
- एक जैसे items के sequence के लिए
Dictionary
- Meaningful key से values
- marks['Maths']
- Records और look-ups के लिए; key से बहुत तेज़ search
सारांश और practice
- Dictionary =
{ }में unique key : value pairs का mutable collection। d[k] = vजोड़ता या update करता है;del d[k]/pop(k)हटाता है।get()KeyError से बचाता है; traversal के लिएitems()सबसे अच्छा।- Frequency गिनना:
d[x] = d.get(x, 0) + 1।
✅ Practice
1) 5 states और capitals की dictionary बनाएँ; user के बताए state की capital print करें। 2) Dictionary invert करें (keys और values बदलें)। 3) Output: d = {1: 'a', 2: 'b'}; d[1] = 'z'; d[3] = 'c'; print(len(d), d)।
Answer 3: 3 {1: 'z', 2: 'b', 3: 'c'}
अक्सर पूछे जाने वाले प्रश्न (FAQ)
क्या dictionary की दो keys same हो सकती हैं?
नहीं। Keys unique होनी चाहिए। किसी मौजूदा key को value assign करें तो पुरानी value बदल जाती है।
Dictionary key क्या हो सकती है?
कोई भी immutable type: numbers, strings या tuples (जिनमें immutable items हों)। Lists और dictionaries keys नहीं बन सकतीं क्योंकि वे mutable हैं।
d[key] और d.get(key) में क्या फ़र्क है?
Key न हो तो d[key] KeyError देता है। d.get(key) error की जगह None (या आपका दिया default, जैसे d.get(key, 0)) देता है।
