PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Dictionary Keys Rules: Keys must be Immutable and Hashable (डिक्शनरी कीज़ के नियम: कीज़ का इम्यूटेबल (int, str, tuple) होना) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।
Overview: In Python, every dictionary key must be hashable, meaning it implements __hash__() returning an unchanging integer across its lifetime and __eq__() for equality comparison. Standard immutable built-ins like int, float, str, bool, and frozenset make valid keys, whereas mutable built-ins like list, set, and dict raise TypeError: unhashable type.
अध्याय सार: पायथन में प्रत्येक डिक्शनरी की (key) का हैशेबल होना अनिवार्य है, अर्थात् उसमें __hash__() (जो पूरे जीवनकाल में स्थिर पूर्णांक लौटाए) और तुलना के लिए __eq__() मेथड होने चाहिए। int, float, str, bool और frozenset जैसे मानक इम्यूटेबल टाइप्स मान्य कीज़ हैं, जबकि list, set और dict जैसे म्यूटेबल टाइप्स TypeError: unhashable type त्रुटि देते हैं।
Dictionary Keys Rules: Keys must be Immutable and Hashable: Detailed Notes & Architecture (डिक्शनरी कीज़ के नियम: कीज़ का इम्यूटेबल (int, str, tuple) होना)
1. The Hashability Contract (__hash__ and __eq__) (हैशेबिलिटी का नियम (__hash__ और __eq__))
[EN] To serve as a dictionary key, an object must obey Python's hash invariant: whenever a == b is True, hash(a) == hash(b) must also hold True. If an object's hash changed after insertion into a hash table, lookups would probe the wrong bucket and fail to locate the entry. For this reason, mutable built-ins explicitly set __hash__ = None, and any user-defined class that overrides __eq__() without explicitly defining __hash__() automatically becomes unhashable.
[HI] डिक्शनरी की बनने के लिए किसी ऑब्जेक्ट को हैश नियम का पालन करना होता है: यदि a == b सत्य है, तो hash(a) == hash(b) भी अवश्य बराबर होना चाहिए। यदि हैश टेबल में डालने के बाद की का हैश बदल जाए, तो खोज गलत स्लॉट पर जाएगी। इसी कारण म्यूटेबल टाइप्स में __hash__ = None होता है, और कोई भी कस्टम क्लास जो __eq__() को ओवरराइड करती है पर __hash__() परिभाषित नहीं करती, स्वतः अनहैशेबल हो जाती है।
2. Valid Immutable Keys vs Unhashable Types (मान्य इम्यूटेबल कीज़ बनाम अनहैशेबल टाइप्स)
[EN] Immutable primitives—int, float, complex, str, bytes, bool, None, range, and frozenset—all implement stable __hash__() methods and work reliably as keys. Even functions, classes, and default user-defined instances (which hash by object identity id()) are hashable. Conversely, list, dict, set, and bytearray are mutable and therefore unhashable, immediately raising TypeError: unhashable type when passed as a key.
[HI] इम्यूटेबल प्रिमिटिव टाइप्स—int, float, complex, str, bytes, bool, None, range और frozenset—स्थिर __hash__() रखते हैं और कीज़ के रूप में मान्य हैं। यहाँ तक कि फ़ंक्शन, क्लास और डिफ़ॉल्ट कस्टम ऑब्जेक्ट्स (जो आइडेंटिटी id() पर हैश होते हैं) भी हैशेबल होते हैं। इसके विपरीत list, dict, set और bytearray म्यूटेबल होने के कारण अनहैशेबल हैं और की बनाने पर TypeError देते हैं।
3. The Nested Tuple Key Rule (नेस्टेड टपल कीज़ का विशेष नियम)
[EN] A common exam trap involves tuples: although tuple itself is immutable, a tuple is hashable only if ALL of its nested elements are recursively hashable. Thus (10, 'cs', frozenset({1, 2})) is a valid dictionary key, whereas (10, [1, 2]) fails with TypeError: unhashable type: 'list' because it embeds a mutable list. Python evaluates hashability recursively across tuple items at the moment hash() is computed.
[HI] परीक्षा में टपल से जुड़ा एक प्रमुख अपवाद पूछा जाता है: यद्यपि tuple स्वयं इम्यूटेबल है, फिर भी यह तभी हैशेबल होता है जब इसके भीतर के सभी नेस्टेड तत्व भी हैशेबल हों। अतः (10, 'cs', frozenset({1, 2})) मान्य डिक्शनरी की है, लेकिन (10, [1, 2]) में म्यूटेबल लिस्ट होने के कारण TypeError: unhashable type: 'list' आता है। पायथन टपल का हैश निकालते समय सभी आंतरिक तत्वों की हैशेबिलिटी जाँचता है।
4. Numeric Equivalence Collisions: 1 == True == 1.0 (संख्यात्मक समानता टकराव: 1 == True == 1.0)
[EN] Because bool is a subclass of int and Python ensures hash(1) == hash(1.0) == hash(True), inserting {1: 'int', True: 'bool', 1.0: 'float'} creates only ONE entry, not three. When an incoming key matches an existing key via ==, Python updates the value in place while preserving the ORIGINAL first key object, yielding {1: 'float'}. Similarly, 0, False, and 0.0 collide into a single key slot, whereas '1' (str) and 1 (int) remain completely distinct keys because '1' != 1.
[HI] चूँकि bool वास्तव में int की सबक्लास है और hash(1) == hash(1.0) == hash(True) होता है, इसलिए {1: 'int', True: 'bool', 1.0: 'float'} लिखने पर तीन के बजाय केवल एक ही एंट्री बनती है। टकराव होने पर पायथन केवल वैल्यू बदलता है और पहली वाली मूल की को ही सुरक्षित रखता है, जिससे {1: 'float'} मिलता है। इसी तरह 0, False और 0.0 एक ही स्लॉट साझा करते हैं, जबकि '1' (स्ट्रिंग) और 1 (पूर्णांक) अलग-अलग कीज़ रहती हैं।
Syntax, Formula & Technical Example (Dictionary Keys Rules: Keys must be Immutable and Hashable)
d1 = {1: 'int', True: 'bool', 1.0: 'float'}
print(d1) # Output: {1: 'float'}
d2 = {(1, 2): 'ok', None: 'empty', '1': 'str'}
print(len(d2), d2[(1, 2)]) # Output: 3 ok
try:
bad = {(1, [2, 3]): 'fail'}
except TypeError as err:
print(type(err).__name__) # Output: TypeError
Dictionary Keys Rules: Keys must be Immutable and Hashable Quick Reference & Comparison Table
| Key Candidate | Hashable Status | Exam Reason |
|---|---|---|
| str / int / frozenset | Valid hashable key | Immutable with fixed __hash__ value |
| (10, 'py') | Valid tuple key | All nested items are immutable |
| (10, [1, 2]) | Raises TypeError | Contains unhashable mutable list |
| list / set / dict | Unhashable (__hash__ is None) | Mutation would break hash table lookup |
Dictionary Keys Rules: Keys must be Immutable and Hashable Top 20 Bilingual MCQs with Answers
Q1. What is the output of d = {1: 'A', True: 'B', 1.0: 'C'}; print(d)?
(d = {1: 'A', True: 'B', 1.0: 'C'}; print(d) का आउटपुट क्या होगा?)
(A) {1: 'A', True: 'B', 1.0: 'C'}
(B) {1: 'C'}
(C) {True: 'B', 1.0: 'C'}
(D) {1.0: 'C'}
Correct Answer: (B)
[EN] 1 == True == 1.0 and all share identical hashes, so Python keeps the first key (1) and overwrites its value up to 'C'.
[HI] 1 == True == 1.0 होने और समान हैश रखने के कारण पायथन पहली की (1) को रखकर मान को 'C' तक ओवरराइट करता है।
Q2. Which error is raised when attempting to use a list as a dictionary key?
(लिस्ट को डिक्शनरी की के रूप में उपयोग करने पर कौन-सी त्रुटि आती है?)
(A) ValueError: invalid key
(B) KeyError: unhashable list
(C) IndexError
(D) TypeError: unhashable type: 'list'
Correct Answer: (D)
[EN] Using any unhashable object as a dictionary key raises TypeError.
[HI] किसी भी अनहैशेबल ऑब्जेक्ट को डिक्शनरी की बनाने पर TypeError उत्पन्न होता है।
Q3. Which tuple can be used as a Python dictionary key without error?
(निम्नलिखित में से कौन-सा टपल बिना त्रुटि के डिक्शनरी की बन सकता है?)
(A) ({1: 2}, 3)
(B) ({1, 2}, 3)
(C) (1, [2, 3])
(D) (1, 'a', frozenset({2, 3}))
Correct Answer: (D)
[EN] A tuple is hashable only when every element inside it is hashable; frozenset is hashable, while list, dict, and set are not.
[HI] टपल तभी हैशेबल होता है जब उसके सभी आंतरिक तत्व हैशेबल हों; frozenset हैशेबल है जबकि list, dict और set नहीं।
Q4. What does len({False: 0, 0: 1, 0.0: 2, '0': 3}) return?
(len({False: 0, 0: 1, 0.0: 2, '0': 3}) क्या लौटाता है?)
(A) 3
(B) 2
(C) 4
(D) 1
Correct Answer: (B)
[EN] False, 0, and 0.0 collapse into one key (False), whereas string '0' is not equal to 0, leaving 2 keys.
[HI] False, 0 और 0.0 मिलकर एक की बनते हैं, जबकि स्ट्रिंग '0' अलग की है, अतः कुल 2 कीज़ रहती हैं।
Q5. What happens if you use None as a dictionary key, e.g., {None: 'missing'}?
(यदि डिक्शनरी की के रूप में None का उपयोग किया जाए ({None: 'missing'}) तो क्या होगा?)
(A) Ignored automatically by dict
(B) Raises TypeError: None is unhashable
(C) It succeeds because None is immutable and hashable
(D) Raises ValueError
Correct Answer: (C)
[EN] NoneType implements __hash__() and is immutable, making None a valid dictionary key.
[HI] NoneType इम्यूटेबल और हैशेबल है, इसलिए None एक मान्य डिक्शनरी की के रूप में कार्य करता है।
Q6. Which built-in byte sequence type CANNOT be used as a dictionary key?
(कौन-सा बिल्ट-इन बाइट सीक्वेंस टाइप डिक्शनरी की के रूप में उपयोग नहीं किया जा सकता?)
(A) str
(B) range
(C) bytearray
(D) bytes
Correct Answer: (C)
[EN] bytearray is mutable and sets __hash__ = None, whereas bytes, str, and range are immutable and hashable.
[HI] bytearray म्यूटेबल है और इसका __hash__ मान None होता है, जबकि bytes, str और range हैशेबल हैं।
Q7. What happens to __hash__ when a custom Python class defines __eq__ without defining __hash__?
(जब कोई कस्टम पायथन क्लास __hash__ परिभाषित किए बिना __eq__ को ओवरराइड करती है, तो __hash__ का क्या होता है?)
(A) Raises SyntaxError at class definition
(B) Python automatically hashes all attributes
(C) It continues hashing by object id()
(D) Python sets __hash__ = None, making instances unhashable
Correct Answer: (D)
[EN] To prevent violating the invariant a == b => hash(a) == hash(b), Python disables __hash__ whenever __eq__ is overridden alone.
[HI] a == b => hash(a) == hash(b) नियम टूटने से बचाने के लिए, अकेले __eq__ ओवरराइड करने पर पायथन __hash__ को None कर देता है।
Q8. Which condition must all hashable objects satisfy in Python?
(पायथन में सभी हैशेबल ऑब्जेक्ट्स को किस नियम का पालन करना आवश्यक है?)
(A) If hash(a) == hash(b), then a == b must be True
(B) If a == b, then hash(a) == hash(b)
(C) hash(a) must always be positive
(D) a and b must have identical types
Correct Answer: (B)
[EN] Equal objects must have equal hashes, though unequal objects may occasionally share a hash (hash collision).
[HI] समान ऑब्जेक्ट्स का हैश समान होना अनिवार्य है, यद्यपि असमान ऑब्जेक्ट्स का हैश कभी-कभी टकरा सकता है।
Q9. What is the key in the resulting dictionary after running d = {True: 'x'}; d[1] = 'y'?
(d = {True: 'x'}; d[1] = 'y' चलाने के बाद परिणामी डिक्शनरी में की (key) क्या होगी?)
(A) True (with value 'x')
(B) True (with value 'y')
(C) 1 (with value 'y')
(D) Both True and 1 exist as separate keys
Correct Answer: (B)
[EN] Updating an existing matching key replaces the value ('y') but retains the original key object (True).
[HI] मौजूदा समान की को अपडेट करने पर केवल वैल्यू ('y') बदलती है और मूल की ऑब्जेक्ट (True) वही रहता है।
Q10. Can a Python function object (def f(): pass) be used as a dictionary key?
(क्या किसी पायथन फ़ंक्शन ऑब्जेक्ट (def f(): pass) को डिक्शनरी की के रूप में उपयोग किया जा सकता है?)
(A) Yes, functions are hashable by default
(B) No, functions are callable not hashable
(C) Only built-in functions work
(D) Only lambda functions are hashable
Correct Answer: (A)
[EN] User-defined functions inherit object's identity-based __hash__() and __eq__(), so they are valid dictionary keys.
[HI] यूज़र-डिफाइंड फ़ंक्शन आइडेंटिटी-आधारित __hash__() रखते हैं, इसलिए वे मान्य डिक्शनरी की होते हैं।
Q11. What does hash((1, 2, [3])) raise?
(hash((1, 2, [3])) कौन-सा अपवाद उत्पन्न करता है?)
(A) TypeError
(B) NameError
(C) KeyError
(D) AttributeError
Correct Answer: (A)
[EN] Computing the hash of a tuple invokes hash() on each element, failing with TypeError on the unhashable list [3].
[HI] टपल का हैश निकालते समय उसके प्रत्येक तत्व का हैश जाँचा जाता है, जिससे लिस्ट [3] पर TypeError आता है।
Q12. Which of the following is hashable in Python 3?
(पायथन 3 में निम्नलिखित में से कौन हैशेबल है?)
(A) [1, 2, 3]
(B) bytearray(b'abc')
(C) {1: 2}
(D) range(1, 10)
Correct Answer: (D)
[EN] In Python 3, range objects are immutable sequences implementing __hash__() and __eq__().
[HI] पायथन 3 में range ऑब्जेक्ट इम्यूटेबल सीक्वेंस है जिसमें __hash__() और __eq__() परिभाषित होते हैं।
Q13. What value type does hash(key) always return in Python?
(पायथन में hash(key) हमेशा किस डेटा टाइप का मान लौटाता है?)
(A) str (hex digest)
(B) float
(C) int
(D) bytes
Correct Answer: (C)
[EN] Python's built-in hash() function always returns a platform-sized signed integer (int).
[HI] पायथन का बिल्ट-इन hash() फ़ंक्शन हमेशा एक पूर्णांक (int) मान लौटाता है।
Q14. Why are hash values for strings randomized across separate Python process runs (PYTHONHASHSEED)?
(अलग-अलग पायथन प्रोसेस रन में स्ट्रिंग के हैश मान (PYTHONHASHSEED) क्यों बदलते रहते हैं?)
(A) Because strings are mutable in CPython
(B) To sort keys alphabetically
(C) To prevent hash-flooding Denial-of-Service (HashDoS) attacks
(D) To compress string memory usage
Correct Answer: (C)
[EN] Since Python 3.3, randomized string hashing prevents attackers from crafting colliding dictionary keys to degrade lookup to O(n).
[HI] पायथन 3.3 से रैंडमाइज्ड स्ट्रिंग हैशिंग लागू की गई ताकि हमलावर जानबूझकर कोलाइडिंग कीज़ बनाकर HashDoS हमला न कर सकें।
Q15. What happens when you create d = {(1, {2, 3}): 'val'} in Python?
(पायथन में d = {(1, {2, 3}): 'val'} बनाने पर क्या होता है?)
(A) Converts {2, 3} into a frozenset
(B) Creates a dictionary with tuple key
(C) Raises TypeError: unhashable type: 'set'
(D) Raises KeyError
Correct Answer: (C)
[EN] Although the outer container is a tuple, it contains a mutable set {2, 3}, making the entire tuple unhashable and raising TypeError.
[HI] यद्यपि बाहरी कंटेनर एक टपल है, लेकिन इसके भीतर एक म्यूटेबल सेट {2, 3} है, जिससे पूरा टपल अनहैशेबल हो जाता है और TypeError आता है।
Q16. Which statement is NOT true regarding Python dictionary keys?
(पायथन डिक्शनरी कीज़ के बारे में कौन-सा कथन सत्य नहीं है?)
(A) Any tuple is always hashable regardless of its elements
(B) Strings and integers are valid keys
(C) Duplicate keys overwrite existing values
(D) Mutable sets cannot be keys
Correct Answer: (A)
[EN] A tuple is only hashable if all elements inside it are also hashable; a tuple containing a list raises TypeError.
[HI] कोई टपल तभी हैशेबल होता है जब उसके भीतर के सभी तत्व भी हैशेबल हों; लिस्ट वाला टपल TypeError देता है।
Q17. Within Dictionary Keys Rules: Keys must be Immutable and Hashable, which key candidate directly maps to: "Valid hashable key"?
(Dictionary Keys Rules: Keys must be Immutable and Hashable में कौन सा Key Candidate सीधे "Valid hashable key" से संबंधित है?)
(A) (10, 'py')
(B) (10, [1, 2])
(C) list / set / dict
(D) str / int / frozenset
Correct Answer: (D)
[EN] In Dictionary Keys Rules: Keys must be Immutable and Hashable, 'str / int / frozenset' handles 'Valid hashable key' (Immutable with fixed __hash__ value).
[HI] Dictionary Keys Rules: Keys must be Immutable and Hashable में 'str / int / frozenset' का कार्य/विवरण 'Valid hashable key' (Immutable with fixed __hash__ value) है।
Q18. Which option accurately describes '(10, 'py')' in Dictionary Keys Rules: Keys must be Immutable and Hashable?
(Dictionary Keys Rules: Keys must be Immutable and Hashable के संदर्भ में '(10, 'py')' की सही विशेषता कौन सी है?)
(A) Raises TypeError
(B) Valid hashable key
(C) Valid tuple key
(D) Unhashable (__hash__ is None)
Correct Answer: (C)
[EN] '(10, 'py')' provides 'Valid tuple key' — key point: All nested items are immutable.
[HI] '(10, 'py')' का मुख्य विवरण 'Valid tuple key' है (All nested items are immutable)।
Q19. In Dictionary Keys Rules: Keys must be Immutable and Hashable, identify the correct parameter for the specification: "Raises TypeError".
(Dictionary Keys Rules: Keys must be Immutable and Hashable में "Raises TypeError" विवरण किस विकल्प के लिए सही है?)
(A) str / int / frozenset
(B) (10, [1, 2])
(C) (10, 'py')
(D) list / set / dict
Correct Answer: (B)
[EN] '(10, [1, 2])' corresponds to 'Raises TypeError' (Contains unhashable mutable list).
[HI] '(10, [1, 2])' का संबंध 'Raises TypeError' (Contains unhashable mutable list) से है।
Q20. Considering Dictionary Keys Rules: Keys must be Immutable and Hashable, what key behavior defines 'list / set / dict'?
(Dictionary Keys Rules: Keys must be Immutable and Hashable में 'list / set / dict' की मुख्य भूमिका या मान क्या है?)
(A) Valid tuple key
(B) Raises TypeError
(C) Unhashable (__hash__ is None)
(D) Valid hashable key
Correct Answer: (C)
[EN] 'list / set / dict' represents 'Unhashable (__hash__ is None)' (Mutation would break hash table lookup).
[HI] 'list / set / dict' का अर्थ/मान 'Unhashable (__hash__ is None)' है (Mutation would break hash table lookup)।
Dictionary Keys Rules: Keys must be Immutable and Hashable — Exam FAQs
Q1: Why is (1, [2, 3]) rejected as a dictionary key even though tuples are immutable?
टपल इम्यूटेबल होने के बावजूद (1, [2, 3]) को डिक्शनरी की क्यों नहीं बनाया जा सकता?
[EN] Although the tuple itself cannot be resized or reassigned, the nested list inside it can be mutated, which would change its contents and break hash stability.
[HI] यद्यपि टपल का आकार नहीं बदल सकता, लेकिन उसके भीतर मौजूद लिस्ट को बदला जा सकता है, जिससे डेटा और हैश स्थिरता भंग हो जाएगी।
Q2: Why does {1: 'A', True: 'B'} result in a dictionary of length 1?
{1: 'A', True: 'B'} की लंबाई 1 क्यों होती है?
[EN] In Python, bool subclasses int so True == 1 and hash(True) == hash(1); the dictionary treats them as identical keys and updates the value for key 1.
[HI] पायथन में bool वास्तव में int की सबक्लास है, इसलिए True == 1 और दोनों का हैश बराबर होता है; डिक्शनरी इन्हें एक ही की मानकर मान अपडेट कर देती है।
Q3: Can an empty tuple () be used as a dictionary key?
क्या खाली टपल () को डिक्शनरी की के रूप में उपयोग किया जा सकता है?
[EN] Yes, () contains zero unhashable items, has a fixed hash value, and works reliably as a dictionary key.
[HI] हाँ, () में कोई अनहैशेबल तत्व नहीं होता और इसका हैश मान स्थिर रहता है, इसलिए यह मान्य डिक्शनरी की है।
Post a Comment
Post a Comment