Testing for an empty dictionary in Python

Ryan Ginstrom software at ginstrom.com
Sun Mar 23 11:51:22 EDT 2008


> On Behalf Of John Nagle
>    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).

I believe that the following is fairly efficient:

>>> def dict_is_empty(D):
	for k in D:
		return False
	return True

>>> dict_is_empty(dict(a=1))
False
>>> dict_is_empty({})
True

Regards,
Ryan Ginstrom




More information about the Python-list mailing list