Testing for an empty dictionary in Python

D'Arcy J.M. Cain darcy at druid.net
Sun Mar 23 16:52:30 CET 2008


On Sun, 23 Mar 2008 08:53:02 -0700
John Nagle <nagle at animats.com> wrote:
>    What's the cheapest way to test for an empty dictionary in Python?
> 
> 	if len(dict.keys() > 0) :
> 
> is expensive for large dictionaries, and makes loops O(N^2).

Try this:

    if dict:

It should be faster as it only checks whether or not there are
any members and does not run keys() or len() on the dictionary.  Of
course, you should test it.

-- 
D'Arcy J.M. Cain <darcy at druid.net>         |  Democracy is three wolves
http://www.druid.net/darcy/                |  and a sheep voting on
+1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.



More information about the Python-list mailing list