Re: Testing for an empty dictionary in Python



On Mar 24, 2:53 am, John Nagle <na...@xxxxxxxxxxx> wrote:
What's the cheapest way to test for an empty dictionary in Python?

if len(dict.keys() > 0) :

TypeError: object of type 'bool' has no len()

I presume you meant
if len(dict.keys()) > 0:


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

I don't understand "makes loops O(N^2)" ... what I see in the
dict_keys function in Objects/dictobject.c is that it makes one linear
pass through its table, ignoring unused and formerly-used slots; seems
like O(N) where N is the size of the table. Where did you get O(N^2)
from?
.



Relevant Pages

  • RE: Dict Copy & Compare
    ... The most straight-forward way is doing a simple pair of loops: ... Membership testing in dicts is efficient, so that should run quite fast ... unless you have millions of keys common to both dictionaries. ...
    (comp.lang.python)
  • Re: True inconsistency in Python
    ... >> he added bool, True, and False, but he wouldn't listen... ... 1000 loops, best of 3: 1.26e+03 usec per loop ... bounded your performance loss to 30-50% when compared to the simplest ...
    (comp.lang.python)
  • Re: Declaring local variables inside loop
    ... Robert Klemme wrote: ... I presume it's something to do with the different structures of our test code ... in terms of what loops are in what methods, and which methods get called /in/ ...
    (comp.lang.java.programmer)
  • Coding Nested Loops
    ... I want to code what would be nested "for" loops in C, ... most elegant way of doing the same thing in python. ... one of three strings held in dictionaries, the last 28 fields are random ...
    (comp.lang.python)
  • Re: interview question on primes
    ... I basically wrote an initial function, bool ... loops over all numbers between 2 and sqrtto see ... What type of software job were you interviewing for? ... I spent many years as a so-called software engineer in the financial world, and never once had to find a prime number. ...
    (sci.math)