Reputation: 9561
What is the shortest way to check for the existence of a certain key/value pair in a dictionary if I don't know that the key exists?
So far, I've come up with:
if 'key' in my_dict and my_dict['key'] == 'value':
do_something()
This is really long with longer variable names or longer key/value names, such as:
if 'X-Powered-By' in self.request.headers and self.request.headers['X-Powered-By'] == 'NodeBB':
do_something()
What's a shorter way to check for the presence of a key and a corresponding value?
Upvotes: 2
Views: 1370
Reputation: 6112
If you're just looking for existence of the key
if not 'key' in my_dict:
my_dict['key'] = 'some default value'
Upvotes: 0
Reputation: 8437
Ok, my suggestion, to make your code more readable:
headers = self.request.headers
if headers.get('X-Powered-By') == 'NodeBB':
do_something()
This could be another short code but definitely not efficient as a dict.get
:
if ('X-Powered-By', 'NodeBB') in self.request.headers.items():
do_something()
Upvotes: -1
Reputation: 73450
Actually, none of the answers captures the full problem. If the value that is being queried for happens to be None
or whatever default value one provides, the get()
-based solutions fail. The following might be the most generally applicable solution, not relying on defaults, truly checking the existence of a key (unlike get()
), and not over-'except'-ing KeyError
s (unlike the other try-except
answer) while still using O(1)
dict
lookup (unlike items()
approach):
try:
assert my_dict[key] == value:
except (KeyError, AssertionError):
do_sth_else() # or: pass
else:
do_something()
Upvotes: 2
Reputation: 29390
You can fetch the value, and compare it right away:
# default return value is None if key is not found
if mydict.get("key") == "somevalue"
or
# Or specify your own default value
if mydict.get("key", False) == "somevalue"
Check out Python dict.get docs.
Upvotes: 8