Testing for an empty dictionary in Python

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Mar 23 20:32:05 EDT 2008


On Sun, 23 Mar 2008 10:45:38 -0700, Paul Rubin wrote:

> John Nagle <nagle at animats.com> writes:
>>    What's the cheapest way to test for an empty dictionary in Python?
>> 
>> 	if len(dict.keys() > 0) :
> 
> I like to think len(dict) is constant time but I haven't checked the
> code. Same for bool(dict) (which is what you get when you run "if dict:
> ...").

Except that "if dict" doesn't needlessly and wastefully create a bool.

>>> from timeit import Timer
>>> Timer("if {1:2}: pass").timeit()
1.1590199184417725
>>> Timer("if bool({1:2}): pass").timeit()
1.8825540542602539


Python knows the truth value of built-in types like dicts without 
actually converting them to bools, or for that matter calling __len__ or 
__nonzero__ on them.




-- 
Steven



More information about the Python-list mailing list