Skip to content
Advertisement

Check if a given key already exists in a dictionary

I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:

JavaScript

I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?

Advertisement

Answer

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

JavaScript

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

JavaScript

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

JavaScript

or use defaultdict from the collections module:

JavaScript
Advertisement