Laizer
Laizer

Reputation: 6150

Testing presence and non-emptyness of dict element

Given a dictionary dict, is there a more elegant way to do this test?

if 'key' in dict and dict['key']:

Upvotes: 0

Views: 56

Answers (1)

user2555451
user2555451

Reputation:

You can use dict.get:

if dict.get('key'):

If the key is not found, the method will return None (which evaluates to False). Otherwise, it will return the value associated with the key.

See a demonstration below:

>>> dct = {'a':0, 'b':1}
>>>
>>> dct.get('a')
0
>>> dct.get('b')
1
>>> dct.get('c')  # Returns None with non-existent keys
>>>
>>> bool(dct.get('a'))  # 0 evaluates to False
False
>>> bool(dct.get('b'))  # 1 evaluates to True
True
>>> bool(dct.get('c'))  # The None returned by dict.get evaluates to False
False
>>>

Note that you can also specify a default return value:

>>> dct.get('c', 'not found')
'not found'
>>>

Upvotes: 3

Related Questions