Check if a given key already exists in a dictionary
To get the idea how to do that we first inspect what methods we can call on dictionary. Here are the methods:
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
The brutal method to check if the key already exists may be the get()
method:
d.get("key")
The other two interesting methods items()
and keys()
sounds like too much of work. So let's examine if get()
is the right method for us. We have our dict d
:
d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Printing shows the key we don't have will return None
:
print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1
We may use that to get the info if the key is present or no.
But consider this if we create a dict with a single key:None
:
d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None
Leading that get()
method is not reliable in case some values may be None
.
This story should have a happier ending. If we use the in
comparator:
print('key' in d) #True
print('key2' in d) #False
We get the correct results. We may examine the Python byte code:
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
This shows that in
compare operator is not just more reliable but even faster than get()
.