Check if a Key Exists in a Python Dictionary

To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this:

pets = {'cats': 1, 'dogs': 2, 'fish': 3}

if 'dogs' in pets:
    print('Dogs found!')

# Dogs found!

Performance considerations

A dictionary can be a convenient data structure for counting the occurrence of items. Say for example you want to count the amount of words in a body of text.

While it may seem intuitive to use an if / else pattern like the following to count items:

text = [] # a list of words
word_count = {}
for word in text:
    if word in word_count
        word_count[word] += 1
    else:
        word_word[count] = 1

some people have pointed out that a try / except pattern like the one below can yield better performance. However, there are actually different situations where each pattern is superior.

text = [] # a list of words.

word_count = {}
for word in text:
    try:
        word_count += 1
    except:
        word_count = 1

So when should you use a try / except pattern instead of an if / else pattern? Well, after running some tests it appears that the threshold is roughly 22% of all words in the body of text being unique. Meaning that if less than 22% of all words being counted in the body of text are unique the try / except pattern will be faster.

The try / except pattern is faster when you have a low amount of exceptions that will be raised, in other words there are are a lot of duplicate words or keys that you are counting. So this method would be suitable when you are counting a list that contains a collection of words that are repeated often without many other possible words that may only be counted once.

However, if the words or keys that you are counting are mostly unique, then the cost of raising an exception each time makes the try / except pattern slower than the if / else pattern.

For a more practical comparison, typically 50% - 62% of words in news articles (tested on The Economist, The Guardian and BBC News) are unique, which makes the if / else pattern faster for counting more diverse bodies of text.

Below are some benchmark results from the test:

# dictionary.txt (one word on each line)
if/else: 0.1533535360
try/except: 0.2706389330
total words: 370103
unique words: 370103
ratio: 1.00

# article.txt (article from The Economist)
if/else: 0.0002584480
try/catch: 0.0002763390
total words: 616
unique words: 374
ratio: 0.61

# balanced.txt (text with 22% unique words)
if/else: 0.0002434520
try/catch: 0.0002434670
total words: 895
unique words: 194
ratio: 0.22

For those interested you can review the source code that was used for these tests.


Join the Able Developer Network

If you liked this post you might be interested in the Able developer network, a new place for developers to blog and find jobs.


Ana Almeida picture

Awesome!