Testing for an empty dictionary in Python
John Nagle
nagle at animats.com
Sun Mar 23 16:00:09 EDT 2008
Brian Lane wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> John Nagle wrote:
>> What's the cheapest way to test for an empty dictionary in Python?
>>
>> if len(dict.keys()) :
>>
>> is expensive for large dictionaries, and makes loops O(N^2).
>>
>> John Nagle
>
> if dict:
Cute.
I'd already figured out that
len(dict)
works, which is probably better than
len(dict.keys() > 0
which requires creating a list.
John Nagle
More information about the Python-list
mailing list