By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

Testing for an empty dictionary in Python

P: n/a
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).

John Nagle
Mar 23 '08 #1
Share this Question
Share on Google+
9 Replies


P: n/a
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

Mar 23 '08 #2

P: n/a
On Sun, 23 Mar 2008 08:53:02 -0700
John Nagle <na***@animats.comwrote:
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 <da***@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.
Mar 23 '08 #3

P: n/a
-----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() 0) :

is expensive for large dictionaries, and makes loops O(N^2).

John Nagle
if dict:
...

:)

- --
- ---[Office 68.7F]--[Outside 42.9F]--[Server 100.4F]--[Coaster 68.0F]---
- ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]---
Software, Linux, Microcontrollers http://www.brianlane.com
AIS Parser SDK http://www.aisparser.com
Movie Landmarks Search Engine http://www.movielandmarks.com

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (Darwin)
Comment: Remember Lexington Green!

iD8DBQFH5nz/Iftj/pcSws0RAnnMAJoDX9P0cK+RshuvuRRfkyJ4CPwqxACeMWkF
pq7AKr/qzVWyVat0QiTtUfo=
=bpei
-----END PGP SIGNATURE-----
Mar 23 '08 #4

P: n/a
On Mar 23, 3:53 pm, John Nagle <na...@animats.comwrote:
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).

John Nagle
As others have stated, if <container object>: is false for built-in
container types such as dicts, lists, sets, tuples,...
Its nice to make any of your owh container types follow the same
convention too.

- Paddy.
Mar 23 '08 #5

P: n/a
John Nagle <na***@animats.comwrites:
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: ...").
Mar 23 '08 #6

P: n/a
On Mar 23, 4:14 pm, Paddy <paddy3...@googlemail.comwrote:
On Mar 23, 3:53 pm, John Nagle <na...@animats.comwrote:
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).
John Nagle

As others have stated, if <container object>: is false for built-in
container types such as dicts, lists, sets, tuples,...
Its nice to make any of your own container types follow the same
convention too.

- Paddy.
I missed out *empty* didn't I.
Its false for empty container types.

- Paddy.
Mar 23 '08 #7

P: n/a
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
Mar 23 '08 #8

P: n/a
On Mar 23, 5:45*pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
John Nagle <na...@animats.comwrites:
* *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: ...").
It has to be constant time as it is a lower bound for inserts (which
average to constant time).

--
Arnaud

Mar 23 '08 #9

P: n/a
On Sun, 23 Mar 2008 18:56:51 -0700, John Machin wrote:
>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.

What the 2.5.1 interpreter does is call PyObject_IsTrue, which checks to
see if the built_in or extension type is a mapping (not just a dict)
with a length method and if so calls it; similarly for sequences:

else if (v->ob_type->tp_as_mapping != NULL &&
v->ob_type->tp_as_mapping->mp_length != NULL)
res = (*v->ob_type->tp_as_mapping->mp_length)(v);
else if (v->ob_type->tp_as_sequence != NULL &&
v->ob_type->tp_as_sequence->sq_length != NULL)
res = (*v->ob_type->tp_as_sequence->sq_length)(v);

Was that what you meant by "without ... calling __len__"?

What I meant was that the interpreter *didn't* do was lookup the name
'__len__' via the normal method resolution procedure. There's no need to
search the dict's __dict__ attribute looking for an attribute named
__len__, or indeed any sort of search at all. It's a direct pointer
lookup to get to mp_length.

I didn't mean to imply that Python magically knew whether a dict was
empty without actually checking to see if it were empty. Apologies for
being less than clear.

Also, since I frequently criticize others for confusing implementation
details with Python the language, I should criticize myself as well. What
I described is specific to the CPython implementation -- there's no
requirement for other Python versions to do the same thing.

--
Steven
Mar 24 '08 #10

This discussion thread is closed

Replies have been disabled for this discussion.