Python Notes
Python Dictionaries का complete guide – creation, access, modification, nested dicts, dict comprehension, defaultdict, OrderedDict, और real-world use cases with Hindi explanations और interview questions।
Introduction (परिचय)
Dictionary एक key-value pair collection है। यह Python का सबसे powerful built-in data structure है।
Key Properties: - ✅ Key-Value pairs – हर element key: value के रूप में - ✅ Ordered – Python 3.7+ में insertion order maintain होता है - ✅ Mutable – Add/modify/delete किया जा सकता है - ❌ Duplicate Keys – Keys unique होनी चाहिए (overwrite होती है) - ✅ Keys must be hashable – string, int, tuple (not list/dict) - ⚡ O(1) average lookup by key2. Accessing Values (Values तक पहुँचना)
Output:
3. Adding and Updating
4. Deleting Elements
5. Dictionary Iteration (Traversal)
6. Nested Dictionaries
7. Dictionary Comprehension
8. Special Dict Types (collections module)
9. Time Complexity
| Operation | Average | Worst | Notes |
|---|---|---|---|
d[key] (get) | O(1) | O(n) | Hash collision |
d[key] = v (set) | O(1) | O(n) | Hash collision |
del d[key] | O(1) | O(n) | |
key in d | O(1) | O(n) | |
d.get(key) | O(1) | O(n) | |
len(d) | O(1) | O(1) | |
| Iteration | O(n) | O(n) | |
d.copy() | O(n) | O(n) | |
d.update(e) | O(k) | O(k) | k = len(e) |
💡 Worst case O(n) तब होता है जब बहुत सारे hash collisions हों (extremely rare with Python's hash implementation)।
10. Real-World Examples
11. Interview Questions
Q1: Dictionary में duplicate key add करने पर क्या होता है?
Q2: Dict को value से sort कैसे करें?
Q3: Two dicts को merge कैसे करें?
a = {"x": 1, "y": 2}
b = {"y": 20, "z": 30}
# Python 3.9+
merged = a | b # {'x': 1, 'y': 20, 'z': 30}
# Python 3.5+
merged = {**a, **b} # same
# update()
a.update(b) # in-placeQ4: Dictionary में सबसे common key कैसे ढूँढें?
Q5: Dict keys को list में convert?
Summary
| Feature | Detail |
|---|---|
| Syntax | {key: val, ...} |
| Keys | Unique, hashable |
| Values | Any type |
| Ordered | Python 3.7+ (insertion order) |
| Access | d[key] or d.get(key) |
| Complexity | O(1) average for get/set/delete |
| Special | defaultdict, Counter, OrderedDict |
| Comprehension | {k: v for k, v in iterable} |
🎯 Use Dict when: आपको fast key-based lookup चाहिए – phone book, config, cache, frequency counting।
📤 Output Blocks (Missing Sections)
Section 3 – Adding and Updating Output:
{'name': 'Alice', 'age': 25, 'email': 'alice@email.com'}
26
{'name': 'Alice', 'age': 26, 'email': 'alice@email.com', 'city': 'Delhi', 'phone': '9876543210'}
27
India
Alice
{'a': 1, 'b': 20, 'c': 30}
{'a': 1, 'b': 20, 'c': 30}
{'a': 1, 'b': 20, 'c': 30}Section 4 – Deleting Elements Output:
{'b': 2, 'c': 3, 'd': 4, 'e': 5}
KeyError: 'z'
Popped: 2
{'c': 3, 'd': 4, 'e': 5}
not found
Popped item: ('e', 5)
{'c': 3, 'd': 4}
{}Section 5 – Dictionary Iteration Output:
apple banana cherry date 50 30 20 15 apple: 50 banana: 30 cherry: 20 date: 15 <class 'dict_keys'> ['apple', 'banana', 'cherry', 'date', 'elderberry'] apple: 50 banana: 30 cherry: 20 date: 15 elderberry: 10 elderberry: 10 date: 15 cherry: 20 banana: 30 apple: 50 apple: 50 banana: 30 cherry: 20 date: 15 elderberry: 10
Section 6 – Nested Dictionaries Output:
80000
Social Media
ENGINEERING:
Alice: ₹90,000
Bob: ₹65,000
MARKETING:
Charlie: ₹70,000
Dave: ₹60,000
SALES:
Eve: ₹55,000
{'a.b.c': 1, 'a.b.d': 2, 'a.e': 3, 'f': 4}Section 7 – Dictionary Comprehension Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
{1: 'a', 2: 'b', 3: 'c'}
{'Alice': 85, 'Charlie': 91}
{'apple': 90.0, 'banana': 45.0, 'cherry': 180.0}
{'name': 'Alice', 'age': 25, 'city': 'Delhi'}
{'the': 3, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}Section 8 – Special Dict Types Output:
{'fruit': ['apple', 'banana'], 'veggie': ['carrot', 'pea']}
{'hello': 3, 'world': 2, 'python': 1}
Counter({'s': 4, 'i': 4, 'p': 2, 'm': 1})
[('s', 4), ('i', 4), ('p', 2)]
4
0
Counter({'a': 3, 'b': 2, 'c': 1})
Counter({'a': 1})
Counter({'a': 1, 'b': 1})
Counter({'a': 2, 'b': 1, 'c': 1})
['second', 'third', 'first']
['first', 'second', 'third']Section 10 – Real-World Examples Output:
DB Host: localhost
[('python', 3), ('is', 2), ('great', 1), ('fun', 1)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
['A', 'B', 'C', 'D']Section 11 – Interview Questions Output:
{'a': 3}
{'a': 4}
{'Charlie': 78, 'Alice': 85, 'Bob': 92}
apple⚠️ Common Mistakes
1. ❌ Mutable key use करना (List as key)
💡 Dict keys hashable होनी चाहिए – string, int, tuple OK हैं, list/dict/set नहीं!
2. ❌ KeyError handle नहीं करना
💡 हमेशा.get()use करो याinसे check करो key access करने से पहले।
3. ❌ Iteration के दौरान dict modify करना
💡 Iteration में dict size change करना allowed नहीं – copy बनाओ या comprehension use करो।
4. ❌ == vs is confusion with dicts
a = {"x": 1}
b = {"x": 1}
print(a == b) # True (same content)
print(a is b) # False (different objects!)💡==content compare करता है,isidentity (memory location) check करता है।
5. ❌ Shallow copy में nested changes reflect होना
💡 Nested objects के लिएcopy.deepcopy()use करो,.copy()shallow है!
6. ❌ fromkeys() के साथ mutable default value
💡 fromkeys() same object reference share करता है – mutable default मत दो!7. ❌ Dict ordering assume करना (Python < 3.7)
💡 Python 3.7+ में dict ordered है, पर explicit ordering चाहिए तो OrderedDict safe option है।✅ Key Takeaways
- 🔑 Dictionary एक key-value pair collection है – fast lookup (O(1) average) के लिए best choice।
- 🔐 Keys unique और hashable होनी चाहिए – string, int, tuple OK; list, dict, set ❌।
- 🛡️
d.get(key, default)use करो – KeyError से बचने का safest तरीका। - 📦
defaultdictuse करो जब missing keys पर automatic default value चाहिए (grouping/counting)। - 🔢
Counteruse करो frequency counting के लिए –.most_common()बहुत handy है। - 🔄 Dict comprehension
{k: v for k, v in iterable}– filtering और transformation के लिए elegant। - ⚡ Python 3.9+ में
d1 | d2merge operator use करो – clean और readable। - 📋 Nested dicts को access करते time
.get()chain करो – safe nested access। - 🧠
copy.deepcopy()use करो nested dicts copy करने के लिए – shallow copy pitfall से बचो। - 🎯 Real-world use cases: config files, caching/memoization, graphs, frequency counting, JSON-like data।
❓ FAQ
Q1: Dict और List में क्या difference है?
Answer: List index-based ordered collection है (0, 1, 2...), जबकि Dict key-based collection है। Dict में access O(1) है by key, List में O(n) search करना पड़ता है। जब आपको named access चाहिए (जैसे student["name"]), तो Dict use करो। Sequential data के लिए List best है।
Q2: Dictionary keys में कौन-कौन से types use कर सकते हैं?
Answer: कोई भी hashable (immutable) type – str, int, float, bool, tuple (अगर tuple के अंदर सब immutable हों)। list, dict, set use नहीं कर सकते क्योंकि ये mutable हैं और hash नहीं हो सकते।
Q3: dict.get() और dict[key] में क्या difference है?
Answer: dict[key] missing key पर KeyError raise करता है। dict.get(key, default) missing key पर None (या custom default) return करता है – कोई error नहीं। Production code में .get() prefer करो।
Q4: defaultdict कब use करना चाहिए?
Answer: जब आपको missing keys पर automatic default value चाहिए – जैसे grouping (defaultdict(list)), counting (defaultdict(int)), या nested dicts (defaultdict(dict))। ये regular dict + manual if key not in d check से cleaner है।
Q5: Dict को value से sort कैसे करें?
Answer:
sorted() with key=lambda x: x[1] value पर sort करता है। reverse=True descending order देता है।
Q6: क्या Dictionary thread-safe है Python में?
Answer: Individual operations (get/set/delete) GIL की वजह से atomic हैं, लेकिन compound operations (check-then-update) thread-safe नहीं हैं। Multi-threaded code में threading.Lock use करो या queue.Queue consider करो।
Q7: update() और |= operator में क्या difference है?
Answer: दोनों in-place merge करते हैं। |= Python 3.9+ में available है और ज्यादा readable है। update() सभी Python 3.x versions में काम करता है। Functionality same है – conflicting keys में दूसरे dict की value win करती है।
Q8: Dict comprehension कब use करना चाहिए?
Answer: जब एक existing iterable से dictionary बनानी हो with filtering/transformation। Simple cases में comprehension ज्यादा readable है loops से। लेकिन complex logic हो तो regular loop better है readability के लिए।
🎯 Interview Questions (Advanced)
Q1: __hash__() और __eq__() का dict में क्या role है?
Answer: Dict internally hash table use करता है। जब key insert/lookup होती है, पहले __hash__() call होता है bucket find करने के लिए, फिर __eq__() exact match verify करने के लिए। Custom objects को dict key बनाने के लिए दोनों implement करने होते हैं, और rule है: a == b implies hash(a) == hash(b)।
Q2: Dict internally कैसे implement होता है Python में?
Answer: CPython में dict एक open-addressing hash table है (Python 3.6+ compact dict)। Keys का hash compute होता है, उससे index determine होता है एक internal array में। Collision resolution probing (linear/quadratic) से होता है। Python 3.6+ में एक separate insertion-order array maintain होता है जो ordering guarantee देता है।
Q3: setdefault() vs defaultdict – कब क्या use करें?
Answer:
setdefault() single key के लिए convenient है। defaultdict जब हर missing key पर same pattern चाहिए तो better है – code cleaner और faster होता है।
Q4: Dict का memory usage कैसे optimize करें?
Answer: (1) __slots__ use करो classes में dict eliminate करने के लिए, (2) large dicts के लिए consider sqlite3 या memory-mapped files, (3) sys.getsizeof() से monitor करो, (4) Python 3.6+ compact dict already ~25% less memory use करता है पुराने implementation से।
Q5: Dict view objects (keys/values/items) क्या हैं?
Answer: ये dynamic views हैं – dict change होने पर automatically reflect करते हैं। ये memory efficient हैं (copy नहीं बनाते)। Set operations support करते हैं (intersection, union) keys() और items() views पर। Iteration के दौरान dict modify करना unsafe है।
Q6: Two dicts के common और uncommon keys efficiently कैसे find करें?
Answer:
d1 = {"a": 1, "b": 2, "c": 3}
d2 = {"b": 20, "c": 30, "d": 40}
common = d1.keys() & d2.keys() # {'b', 'c'}
only_d1 = d1.keys() - d2.keys() # {'a'}
only_d2 = d2.keys() - d1.keys() # {'d'}
all_keys = d1.keys() | d2.keys() # {'a', 'b', 'c', 'd'}Dict keys views set operations support करते हैं – O(min(n,m)) time complexity।
Q7: ChainMap क्या है और कब useful है?
Answer:
ChainMap multiple dicts को logical एक dict जैसा treat करता है – first match wins। Configuration layering, scope resolution (like variable lookup in nested scopes) में useful है। Original dicts modify नहीं होते।
Q8: Dict vs namedtuple vs dataclass – कब कौन use करें?
Answer: Dict – dynamic keys, JSON-like data, unknown structure। namedtuple – lightweight immutable records, memory efficient, tuple compatibility। dataclass – structured data with methods, type hints, mutable by default। Rule: अगर fields fixed हैं और type safety चाहिए तो dataclass; immutable lightweight record चाहिए तो namedtuple; dynamic/flexible structure है तो dict।
Q9: Dict में memory leak कैसे हो सकता है?
Answer: (1) Circular references in nested dicts (GC handles but slowly), (2) Dict as cache without size limit – unbounded growth, (3) Holding references to large objects as values। Solution: weakref.WeakValueDictionary use करो, या functools.lru_cache(maxsize=N) caching के लिए, या manual cleanup implement करो।
Q10: | merge operator (Python 3.9+) internally कैसे काम करता है?
Answer: d1 | d2 internally __or__ method call करता है जो: (1) new dict create करता है, (2) d1 के सभी items copy करता है, (3) d2 के items add/overwrite करता है। Time complexity O(n+m) है। |= (in-place) __ior__ call करता है जो existing dict में d2 merge करता है (same as update() internally)।
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Dictionaries – Key-Value Store.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, data, structures, dictionaries
Related Python Master Course Topics