The Python Oracle

Check if a given key already exists in a dictionary

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Check If A Given Key Already Exists In A Dictionary
00:24 Answer 1 Score 1915
00:41 Answer 2 Score 186
00:56 Accepted Answer Score 5579
01:30 Answer 4 Score 298
02:08 Thank you

--

Full question
https://stackoverflow.com/questions/1602...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ACCEPTED ANSWER

Score 5579


in tests for the existence of a key in a dict:

d = {"key1": 10, "key2": 23}

if "key1" in d:
    print("this will execute")

if "nonexistent key" in d:
    print("this will not")

Use dict.get() to provide a default value when the key does not exist:

d = {}

for i in range(100):
    key = i % 10
    d[key] = d.get(key, 0) + 1

To provide a default value for every key, either use dict.setdefault() on each assignment:

d = {}

for i in range(100):
    d[i % 10] = d.setdefault(i % 10, 0) + 1    

...or better, use defaultdict from the collections module:

from collections import defaultdict

d = defaultdict(int)

for i in range(100):
    d[i % 10] += 1



ANSWER 2

Score 1915


Use key in my_dict directly instead of key in my_dict.keys():

if 'key1' in my_dict:
    print("blah")
else:
    print("boo")

That will be much faster as it uses the dictionary's O(1) hashing as opposed to doing an O(n) linear search on a list of keys.




ANSWER 3

Score 298


You can test for the presence of a key in a dictionary, using the in keyword:

d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False

A common use for checking the existence of a key in a dictionary before mutating it is to default-initialize the value (e.g. if your values are lists, for example, and you want to ensure that there is an empty list to which you can append when inserting the first value for a key). In cases such as those, you may find the collections.defaultdict() type to be of interest.

In older code, you may also find some uses of has_key(), a deprecated method for checking the existence of keys in dictionaries (just use key_name in dict_name, instead).




ANSWER 4

Score 186


You can shorten your code to this:

if 'key1' in my_dict:
    ...

However, this is at best a cosmetic improvement. Why do you believe this is not the best way?