Home Ask Login Register

Developers Planet

Your answer is one click away!

skyler February 2016

Get True or False from dict and key's existence

I'm trying to get a boolean True or False value based on whether a dict exists (is not None) and if it contains a value.

This is my code. I would expect enabled == False but it is assigned the value of cfg.

In [105]: cfg = {}

In [106]: is_enabled = cfg and cfg.get('enabled')

In [107]: is_enabled
Out[107]: {}

Why is is_enabled == {}? This must be an obvious mistake but I don't see it.


Matthew February 2016

Do this

is_enabled = cfg is not None and 'enabled' in cfg

MSeifert February 2016

Depending on what you actually want to have to rewrite it

is_enabled = True if (cfg and cfg.get('enabled')) else False

cfg only evaluates to False in a boolean context like if cfg.

Paul Cornelius February 2016

Welcome to the world of short-circuit boolean operators. In the expression cfg and ANYTHING, since cfg is empty it has a boolean value of False. Therefore the second operand is never evaluated. The result of the expression is the first operand, which is {}. Note that the expression 0 and None has a value of 0, but the expression 1 and None has a value of None!

Perhaps you want the line to read is_enabled = bool(cfg) and cfg.get('enabled') or even just is_enabled = cfg.get('enabled',False).

Post Status

Asked in February 2016
Viewed 3,604 times
Voted 5
Answered 3 times


Leave an answer

Quote of the day: live life