Python Notes
Python Dictionary के सभी built-in methods का complete reference – get, keys, values, items, update, pop, popitem, setdefault, copy, clear, fromkeys – examples और time complexity के साथ।
Quick Reference Table
| Method | Syntax | Description | Returns |
|---|---|---|---|
get() | d.get(key[, default]) | Safe key access | Value or default |
keys() | d.keys() | All keys | dict_keys view |
values() | d.values() | All values | dict_values view |
items() | d.items() | All (key, value) pairs | dict_items view |
update() | d.update(other) | Merge/update | None |
pop() | d.pop(key[, default]) | Remove & return value | Value |
popitem() | d.popitem() | Remove & return last pair | (key, value) tuple |
setdefault() | d.setdefault(key[, default]) | Get or insert default | Value |
copy() | d.copy() | Shallow copy | New dict |
clear() | d.clear() | Remove all items | None |
fromkeys() | dict.fromkeys(keys[, val]) | Create from keys | New dict |
2. keys(), values(), items() – View Objects
ये तीनों methods view objects return करते हैं जो dictionary के साथ live रहते हैं।
Output:
3. update() – Dict को Merge/Update करना
Output:
| {'name' | 'Alice', 'age': 25, 'email': 'alice@email.com', 'city': 'Delhi'} |
| {'a' | 1, 'b': 2, 'c': 3} |
| {'a' | 1, 'b': 2, 'c': 3} |
| {'a' | 1, 'b': 2, 'c': 3} |
| {'x' | 1, 'y': 99, 'z': 3} |
4. pop() – Key से Value हटाना व Return करना
data = {"name": "Bob", "age": 30, "city": "Mumbai", "job": "Dev"}
# pop() – remove and return value
age = data.pop("age")
print(f"Popped age: {age}") # Popped age: 30
print(data) # {'name': 'Bob', 'city': 'Mumbai', 'job': 'Dev'}
# pop() with default (no error if missing)
result = data.pop("email", "not set")
print(result) # not set
# pop() without default → KeyError if missing
try:
data.pop("salary")
except KeyError as e:
print(f"KeyError: {e}")
# Pattern: process and remove
config = {"host": "localhost", "port": 5432, "debug": True}
host = config.pop("host") # extract and remove
port = config.pop("port")
print(f"Connecting to {host}:{port}")
print("Remaining config:", config) # {'debug': True}
# Use case: stack-like processing
tasks = {"task1": "high", "task2": "low", "task3": "medium"}
while tasks:
task, priority = tasks.popitem() # LIFO
print(f"Processing {task} ({priority})")Output:
| Popped age | 30 |
| {'name' | 'Bob', 'city': 'Mumbai', 'job': 'Dev'} |
| KeyError | 'salary' |
| Connecting to localhost | 5432 |
| Remaining config | {'debug': True} |
5. popitem() – Last Item हटाना
popitem() – last inserted (key, value) pair हटाता और return करता है।
d = {"a": 1, "b": 2, "c": 3}
# popitem() – removes and returns last (LIFO)
item = d.popitem()
print(item) # ('c', 3)
print(d) # {'a': 1, 'b': 2}
item = d.popitem()
print(item) # ('b', 2)
# Empty dict → KeyError
try:
{}.popitem()
except KeyError as e:
print(f"Error: {e}") # dictionary is empty
# Use case: processing items one by one
inventory = {"item1": 100, "item2": 200, "item3": 300}
processed = []
while inventory:
key, val = inventory.popitem()
processed.append((key, val * 1.1)) # apply 10% markup
print("Processed:", processed)Output:
| {'a' | 1, 'b': 2} |
| Error | 'popitem(): dictionary is empty' |
| Processed | [('item3', 330.0), ('item2', 220.0), ('item1', 110.0)] |
6. setdefault() – Get या Insert Default
dict.setdefault(key, default=None)
- Key exists → value return करे (dict change नहीं होती)
- Key missing → default set करे और return करे
Output:
| {'name' | 'Alice', 'age': 25} |
| {'name' | 'Alice', 'age': 25, 'city': 'Delhi'} |
| {'a' | ['apple', 'avocado', 'apricot'], 'b': ['banana', 'blueberry'], 'c': ['cherry']} |
| {'a' | ['apple', 'avocado', 'apricot'], 'b': ['banana', 'blueberry'], 'c': ['cherry']} |
| {'users' | {'alice': {'role': 'admin'}}} |
7. copy() – Shallow Copy
Output:
8. clear() – सभी Elements हटाना
config = {"host": "localhost", "port": 5432, "debug": True}
print(f"Before clear: {len(config)} items")
config.clear()
print(f"After clear: {config}") # {}
# clear() vs reassignment (reference behavior)
a = {"x": 1, "y": 2}
b = a # same reference
a.clear() # in-place clear
print(a) # {}
print(b) # {} ← b also cleared!
# vs reassignment
a = {"x": 1, "y": 2}
b = a
a = {} # new empty dict assigned to a
print(a) # {}
print(b) # {'x': 1, 'y': 2} ← b unchanged!Output:
| Before clear | 3 items |
| After clear | {} |
| {'x' | 1, 'y': 2} |
9. fromkeys() – Class Method
dict.fromkeys(iterable, value=None) – keys से नया dict बनाता है।
Output:
| {'name' | 'unknown', 'age': 'unknown', 'city': 'unknown', 'email': 'unknown'} |
| {'name' | None, 'age': None, 'city': None, 'email': None} |
| {'h' | 0, 'e': 0, 'l': 0, 'o': 0} |
| {'a' | [1], 'b': [1], 'c': [1]} |
| {'a' | [1], 'b': [], 'c': []} |
| {'Alice' | 10, 'Bob': 5, 'Charlie': 0} |
10. Advanced Patterns
Pattern 1: Counting with get()
[('hello', 3), ('world', 2), ('python', 1)]Pattern 2: Grouping with setdefault()
{'CS': ['Alice', 'Charlie'], 'Math': ['Bob', 'Eve'], 'Physics': ['Dave']}Pattern 3: Dict as Switch/Case
def process(operation, a, b):
ops = {
"add": lambda: a + b,
"sub": lambda: a - b,
"mul": lambda: a * b,
"div": lambda: a / b if b != 0 else "Error"
}
return ops.get(operation, lambda: "Unknown op")()
print(process("add", 10, 5)) # 15
print(process("mul", 4, 7)) # 28
print(process("xyz", 1, 2)) # Unknown op15 28 Unknown op
Pattern 4: Invert a Dictionary
{1: 'a', 2: 'b', 3: 'c'}
{'A': ['Alice', 'Charlie'], 'B': ['Bob'], 'C': ['Dave']}11. View Objects Deep Dive
d = {"a": 1, "b": 2, "c": 3}
k = d.keys()
v = d.values()
i = d.items()
print(type(k)) # <class 'dict_keys'>
print(type(v)) # <class 'dict_values'>
print(type(i)) # <class 'dict_items'>
# Views support set-like operations (keys and items)
d1 = {"a": 1, "b": 2, "c": 3}
d2 = {"b": 20, "c": 30, "d": 40}
# Common keys
common_keys = d1.keys() & d2.keys()
print(common_keys) # {'b', 'c'}
# Keys only in d1
only_d1 = d1.keys() - d2.keys()
print(only_d1) # {'a'}
# Common (key, value) pairs
common_items = d1.items() & d2.items()
print(common_items) # set() (no matching key-value pairs)
# values() does NOT support set operations (values may be unhashable)
# d1.values() & d2.values() → TypeError<class 'dict_keys'>
<class 'dict_values'>
<class 'dict_items'>
{'b', 'c'}
{'a'}
set()12. Method vs Operator Comparison
d1 = {"a": 1, "b": 2}
d2 = {"b": 20, "c": 30}
# Merge (new dict)
m1 = {**d1, **d2} # Python 3.5+ unpacking
m2 = d1 | d2 # Python 3.9+ operator
m3 = dict(d1)
m3.update(d2) # update method
print(m1 == m2) # True
print(m2 == m3) # True
# In-place merge
d1 |= d2 # Python 3.9+ operator
# vs
d1.update(d2) # method (equivalent)True True
13. Interview Questions
Q1: get() और [] access में क्या difference है?
d[key]– key missing होने परKeyErrorraise होता है।d.get(key, default)– key missing होने परNone(या custom default) return करता है, no exception।
Q2: keys(), values(), items() क्या return करते हैं?
ये view objects return करते हैं, static list नहीं। Views live हैं – dict change होने पर automatically reflect होती है। List चाहिए तो list(d.keys()) use करें।Q3: setdefault() का best use case क्या है?
Grouping items या nested structure initialize करने के लिए:
groups = {}
for item in items:
groups.setdefault(item.category, []).append(item)Q4: fromkeys() में mutable default क्यों dangerous है?
Q5: pop() और popitem() में क्या difference है?
pop(key)– specific key हटाता है, value return करता है।popitem()– last inserted (key, value) pair हटाता है, tuple return करता है।
Summary Cheatsheet
⚠️ Common Mistakes
Mistake 1: fromkeys() में Mutable Default Use करना ❌
{'a': [1], 'b': [1], 'c': [1]}{'a': [1], 'b': [], 'c': []}Mistake 2: update() का Return Value Use करना ❌
# ❌ WRONG – update() returns None, not the dict!
d = {"a": 1}
result = d.update({"b": 2})
print(result) # None 😵None
# ✅ RIGHT – update() in-place काम करता है
d = {"a": 1}
d.update({"b": 2})
print(d) # {'a': 1, 'b': 2}{'a': 1, 'b': 2}Mistake 3: Loop में Dict Size Change करना ❌
{'c': 3}Mistake 4: copy() को Deep Copy समझना ❌
[1, 2, 3, 4]
[1, 2, 3]
Mistake 5: pop() बिना Default के Missing Key पर ❌
# ❌ WRONG – KeyError if key doesn't exist
d = {"name": "Alice"}
# val = d.pop("email") # KeyError: 'email'
# ✅ RIGHT – default value provide करो
val = d.pop("email", None)
print(val) # None (no error)None
Mistake 6: clear() और Reassignment में Confuse होना ❌
# ❌ Unexpected behavior – references matter!
a = {"x": 1}
b = a
a = {} # a को new dict assign किया
print(b) # {'x': 1} – b अभी भी old dict point कर रहा है!
# ✅ clear() in-place सभी references affect करता है
a = {"x": 1}
b = a
a.clear()
print(b) # {} – both cleared{'x': 1}
{}Mistake 7: View Objects को List की तरह Index करना ❌
a
✅ Key Takeaways
- 🔑
get()always prefer करो[]access के बजाय जब key exist करना uncertain हो – KeyError से बचो! - 🔄 View objects live हैं –
keys(),values(),items()dictionary changes automatically reflect करते हैं - 📦
setdefault()= get + insert – key missing हो तो default set करके return करता है, grouping के लिए perfect - ⚡
update()returns None – यह in-place operation है, chain करने के लिए|operator (Python 3.9+) use करो - 🗑️
pop()vspopitem()–pop(key)specific key हटाता है,popitem()last inserted item (LIFO order) - 📋
fromkeys()+ mutable = danger – list/dict default सभी keys share करते हैं, comprehension use करो - 🧬
copy()= shallow only – nested objects के लिएcopy.deepcopy()ज़रूरी है - 🧹
clear()vs= {}–clear()सभी references affect करता है, reassignment नया object बनाता है - 🔗 Set operations on views –
d1.keys() & d2.keys()से common keys मिलते हैं (powerful feature!) - 📊 Time Complexity – ज़्यादातर dict methods O(1) हैं,
update()O(n) जहाँ n = other dict size
❓ FAQ
Q1: get() और setdefault() में क्या difference है?
Answer: get() सिर्फ value return करता है, dictionary modify नहीं करता। setdefault() key missing होने पर default value insert भी करता है dict में और फिर return करता है। अगर आप dict change नहीं चाहते तो get(), अगर missing key पर auto-insert चाहते हो तो setdefault() use करो।
Q2: Dict views को list में convert करने की ज़रूरत कब होती है?
Answer: जब आपको indexing (keys[0]), slicing (keys[:3]), या repeated iteration with modification चाहिए। Views indexing support नहीं करते। हालांकि, simple iteration और in check के लिए views directly use करना ज़्यादा efficient है – extra memory नहीं लगती।
Q3: popitem() किस order में items remove करता है?
Answer: Python 3.7+ में popitem() LIFO (Last-In, First-Out) order follow करता है – last inserted item पहले remove होता है। Python 3.6 से पहले dict unordered था, तो popitem() arbitrary item return करता था। Modern Python में dict insertion order maintain करता है।
Q4: d1 | d2 और d1.update(d2) में क्या difference है?
Answer: d1 | d2 (Python 3.9+) एक new dict return करता है, original dicts unchanged रहते हैं। d1.update(d2) in-place modify करता है d1 को और None return करता है। Functional programming style में | prefer करो, in-place modification चाहिए तो update() use करो।
Q5: Dictionary iterate करते समय items delete कैसे करें?
Answer: Directly iteration में delete करने से RuntimeError आता है। Solution: list(d.keys()) की copy बनाकर iterate करो, या dict comprehension से new filtered dict बनाओ:
# Safe way
d = {k: v for k, v in d.items() if v >= threshold}Q6: copy() कब sufficient है और deepcopy() कब ज़रूरी है?
Answer: अगर dict में सिर्फ immutable values हैं (int, str, tuple) तो copy() काफ़ी है। अगर nested lists, dicts, या custom objects हैं तो deepcopy() use करो – otherwise nested changes original में reflect होंगे।
Q7: क्या dict.fromkeys() efficient है बड़ी keys list के लिए?
Answer: हाँ, dict.fromkeys() internally optimized है और dict comprehension से slightly faster हो सकता है simple immutable defaults (int, str, None) के लिए। But mutable defaults (list, dict) के लिए हमेशा comprehension use करो – fromkeys एक ही object share करता है।
Q8: setdefault() vs defaultdict – कौनसा better है?
Answer: defaultdict (from collections) better है जब हर access पर default चाहिए – automatically handle करता है। setdefault() better है one-off cases में या जब आप regular dict ही रखना चाहते हो। defaultdict slightly faster भी है heavy usage में क्योंकि Python-level method call avoid होता है।
🎯 Interview Questions (Detailed)
Q1: get() और [] access में क्या difference है? Real-world scenario बताओ।
Answer: d[key] key missing होने पर KeyError raise करता है, जबकि d.get(key, default) gracefully None या custom default return करता है। Real-world: API response parse करते समय response.get("data", {}).get("user", None) safe है – nested missing keys पर crash नहीं होता। Production code में almost always get() prefer करो।
Q2: Dictionary view objects क्या हैं? ये list से कैसे different हैं?
Answer: keys(), values(), items() view objects return करते हैं जो:
- Live/Dynamic हैं – dict change होने पर automatically update होते हैं
- Memory efficient – data copy नहीं करते, original dict point करते हैं
- Set operations support करते हैं (keys और items views)
- Indexing support नहीं करते (
views[0]TypeError देगा)
List static snapshot है, view dynamic reference है।
Q3: setdefault() internally कैसे काम करता है? Time complexity क्या है?
Answer: setdefault(key, default) internally: (1) Check if key exists → O(1) hash lookup, (2) If yes, return existing value, (3) If no, insert key: default pair and return default। Overall O(1) average case। यह atomically "check and set" करता है – race conditions avoid होते हैं single-threaded code में।
Q4: Shallow copy और deep copy का difference code से explain करो।
Answer:
[1, 2, 3, 4] 10
Shallow copy सिर्फ top-level keys copy करता है, nested objects same reference share करते हैं। Deep copy recursively सब copy करता है।
Q5: Dict merge करने के कितने तरीके हैं Python में? Performance compare करो।
Answer:
d1, d2 = {"a": 1}, {"b": 2}
# Method 1: update() – in-place, O(n)
d1.update(d2)
# Method 2: | operator (Python 3.9+) – new dict, O(n+m)
merged = d1 | d2
# Method 3: unpacking (Python 3.5+) – new dict, O(n+m)
merged = {**d1, **d2}
# Method 4: dict() constructor
merged = dict(d1, **d2) # ⚠️ keys must be stringsPerformance: update() fastest for in-place, | और {**} similar for new dict creation। Large dicts के लिए in-place update() memory efficient है।
Q6: popitem() का LIFO behavior कब useful है?
Answer: Stack-like processing में: जब items insert order में process करने हों (last first)। Example: Undo operations, task queue (LIFO), या temporary storage drain करना। Python 3.7+ guarantee करता है insertion order, इसलिए popitem() reliably last item देता है।
Q7: Dictionary iteration के दौरान size change करने पर क्या होता है?
Answer: RuntimeError: dictionary changed size during iteration raise होता है। Solutions:
Python deliberately यह error raise करता है undefined behavior prevent करने के लिए।
Q8: dict.fromkeys() vs dict comprehension – कब कौनसा use करें?
Answer: fromkeys() use करो जब सभी keys को same immutable value assign करना हो (0, None, "default")। Dict comprehension use करो जब: (1) Mutable defaults चाहिए (list, dict), (2) Different values per key चाहिए, (3) Transformation logic apply करनी हो। fromkeys() slightly faster है simple cases में but comprehension ज़्यादा flexible है।
Q9: clear() method कब use करें vs new empty dict assign करना?
Answer: clear() use करो जब multiple references same dict point कर रहे हों और सभी को empty दिखाना हो। d = {} सिर्फ variable rebind करता है, दूसरे references पर कोई effect नहीं। Memory perspective: clear() internal hash table release करता है, reassignment old dict garbage collect होने पर memory free करता है।
Q10: Real interview problem – Two dicts merge करो with custom conflict resolution
Answer:
{'x': 1, 'y': 22, 'z': 33, 'w': 40}
{'x': 1, 'y': [2, 20], 'z': [3, 30], 'w': 40}यह pattern real-world config merging, data aggregation में काम आता है।
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Dictionary Methods – Complete Reference.
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, dictionary
Related Python Master Course Topics