42

How to check if dictionary is empty or not? more specifically, my program starts with some key in dictionary and I have a loop which iterates till there are key in dictionary. Overall algo is like this:

Start with some key in dict
while there is key in dict
do some operation on first key in dict
remove first key

Please note that some operation in above loop may add new keys to dictionary. I've tried for key,value in d.iteritems()

but it is failing as during while loop some new key are added.

username_4567
  • 4,737
  • 12
  • 56
  • 92
  • 15
    `if dict` should check for emptiness. – squiguy Nov 09 '12 at 16:37
  • What are you **really** trying to do? What is the algorithm for, what's in the dict? – Karl Knechtel Nov 09 '12 at 17:40
  • A normal dict is just a hashtable and has no concept of order, 'first' is meaningless. You could use [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) instead if you need this behaviour. – Ed Randall Oct 01 '19 at 06:37

7 Answers7

48

any(d)

This will return true if the dict. d contains at least one truelike key, false otherwise.

Example:

any({0:'test'}) == False

another (more general) way is to check the number of items:

len(d)

Kel Solaar
  • 3,660
  • 1
  • 23
  • 29
Wajih
  • 905
  • 9
  • 13
  • 2
    This is the proper solution according to http://docs.python.org/2/library/functions.html#any – starryknight64 Feb 14 '14 at 22:53
  • 53
    This isn't right. `any(d)` returns True if d contains at least one truelike key. But if the keys are falselike -- for example, `d = {0: 'this dictionary is not empty'}` -- then `any(d)` will be False. – DSM Feb 15 '14 at 02:48
  • 1
    Thanks @DSM modified according to the falselike/truelike keys remark. – Wajih Jun 27 '14 at 09:58
18

I just wanted to know if the dictionary i was going to try to pull data from had data in it in the first place, this seems to be simplest way.

d = {}

bool(d)

#should return
False

d = {'hello':'world'}

bool(d)

#should return
True
falsetru
  • 357,413
  • 63
  • 732
  • 636
noname
  • 181
  • 1
  • 2
18

Just check the dictionary:

d = {'hello':'world'}
if d:
  print 'not empty'
else:
  print 'empty'

d = {}
if d:
  print 'not empty'
else:
  print 'empty'
Eduardo Santana
  • 5,780
  • 3
  • 19
  • 21
15

This will do it:

while d:
    k, v = d.popitem()
    # now use k and v ...

A dictionary in boolean context is False if empty, True otherwise.

There is no "first" item in a dictionary, because dictionaries aren't ordered. But popitem will remove and return some item for you each time.

Jamey Sharp
  • 8,363
  • 2
  • 29
  • 42
8

I would say that way is more pythonic and fits on line:

If you need to check value only with the use of your function:

if filter( your_function, dictionary.values() ): ...

When you need to know if your dict contains any keys:

if dictionary: ...

Anyway, using loops here is not Python-way.

Pavel Daynyak
  • 1,714
  • 1
  • 11
  • 7
2

As far as I know the for loop uses the iter function and you should not mess with a structure while iterating over it.

Does it have to be a dictionary? If you use a list something like this might work:

while len(my_list) > 0:
    #get last item from list
    key, value = my_list.pop()
    #do something with key and value
    #maybe
    my_list.append((key, value))

Note that my_list is a list of the tuple (key, value). The only disadvantage is that you cannot access by key.

EDIT: Nevermind, the answer above is mostly the same.

Karsten
  • 882
  • 6
  • 18
2

Here is another way to do it:

isempty = (dict1 and True) or False

if dict1 is empty then dict1 and True will give {} and this when resolved with False gives False.

if dict1 is non-empty then dict1 and True gives True and this resolved with False gives True

ShikharDua
  • 9,411
  • 1
  • 26
  • 22