473,606 Members | 2,381 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Testing for an empty dictionary in Python

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
9 48684
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
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.ne t | 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
-----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, Microcontroller s 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/pcSws0RAnnMAJoD X9P0cK+RshuvuRR fkyJ4CPwqxACeMW kF
pq7AKr/qzVWyVat0QiTtUf o=
=bpei
-----END PGP SIGNATURE-----
Mar 23 '08 #4
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
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
On Mar 23, 4:14 pm, Paddy <paddy3...@goog lemail.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
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
On Mar 23, 5:45*pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
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
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_mappin g != NULL &&
v->ob_type->tp_as_mappin g->mp_length != NULL)
res = (*v->ob_type->tp_as_mappin g->mp_length)(v );
else if (v->ob_type->tp_as_sequen ce != NULL &&
v->ob_type->tp_as_sequen ce->sq_length != NULL)
res = (*v->ob_type->tp_as_sequen ce->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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3920
by: C Gillespie | last post by:
Dear All, I ran my code through pylint to clean it up and one of the (many) errors it through up was Dangerous default value {} as argument Bascially, I have: class NewClass: def __init__(self, myDict={}): for key, value in myDict: print key, value
31
88585
by: noagbodjivictor | last post by:
How to check if a string is empty in python? if(s == "") ??
6
3887
by: gita ziabari | last post by:
Hello All, The following code does not work for unicode characters: keyword = dict() kw = 'ÇÅÎÓËÉÈ' keyword.setdefault(key, ).append (kw) It works fine for inserting ASCII character. Any suggestion?
0
8016
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
8096
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6773
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5466
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3937
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3980
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2448
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1557
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1300
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.