जांचें कि क्या दी गई कुंजी पहले से ही एक शब्दकोश में मौजूद है
यह विचार करने के लिए कि हम पहले कैसे निरीक्षण करते हैं कि हम किन तरीकों को शब्दकोश में कह सकते हैं। ये तरीके हैं:
d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Python Dictionary clear() Removes all Items
Python Dictionary copy() Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys() Creates dictionary from given sequence
Python Dictionary get() Returns Value of The Key
Python Dictionary items() Returns view of dictionary (key, value) pair
Python Dictionary keys() Returns View Object of All Keys
Python Dictionary pop() Removes and returns element having given key
Python Dictionary popitem() Returns & Removes Element From Dictionary
Python Dictionary setdefault() Inserts Key With a Value if Key is not Present
Python Dictionary update() Updates the Dictionary
Python Dictionary values() Returns view of all values in dictionary
यह जाँचने की क्रूर विधि कि कुंजी पहले से मौजूद है, get()
विधि हो सकती है :
d.get("key")
अन्य दो दिलचस्प तरीके items()
और keys()
आवाज़ बहुत काम की लगती है। तो आइए देखें कि क्या get()
हमारे लिए सही तरीका है। हम अपने तानाशाही d
:
d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
मुद्रण से पता चलता है कि हमारे पास नहीं है None
:
print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1
यदि कुंजी मौजूद है या नहीं तो जानकारी प्राप्त करने के लिए हम इसका उपयोग कर सकते हैं। लेकिन इस पर विचार करें यदि हम एक एकल के साथ एक तानाशाही बनाते हैं key:None
:
d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None
get()
यदि कुछ मान हो सकते हैं तो उस पद्धति का नेतृत्व करना विश्वसनीय नहीं है None
। इस कहानी का सुखद अंत होना चाहिए। यदि हम in
तुलनित्र का उपयोग करते हैं :
print('key' in d) #True
print('key2' in d) #False
हमें सही परिणाम मिलते हैं। हम पायथन बाइट कोड की जांच कर सकते हैं:
import dis
dis.dis("'key' in d")
# 1 0 LOAD_CONST 0 ('key')
# 2 LOAD_NAME 0 (d)
# 4 COMPARE_OP 6 (in)
# 6 RETURN_VALUE
dis.dis("d.get('key2')")
# 1 0 LOAD_NAME 0 (d)
# 2 LOAD_METHOD 1 (get)
# 4 LOAD_CONST 0 ('key2')
# 6 CALL_METHOD 1
# 8 RETURN_VALUE
इससे पता चलता है कि in
ऑपरेटर की तुलना न केवल अधिक विश्वसनीय है, बल्कि उससे भी तेज है get()
।
dict.keys()
प्रलेखन के अनुसार कॉलिंग कुंजी की एक सूची बनाती है, दस्तावेज़ docs.python.org/2/library/stdtypes.html#dict.keys के अनुसार, लेकिन अगर इस पैटर्न को किसी गंभीर कार्यान्वयन में, अनुवाद करने के लिए, अनुकूलित नहीं किया गया तो मुझे आश्चर्य होगा। कोif 'key1' in dict:
।