Hướng dẫn is dict empty python?

Sometimes, we need to check if a particular dictionary is empty or not. In the web development domain in which we sometimes need to test for results of a particular query or check whether we have any key to add info into a database. Let’s discuss certain ways in which this task can be performed in Python. 

Check if a Dictionary is Empty using bool[]

The bool function can be used to perform this particular task. As the name suggests it performs the task of converting an object to a boolean value, but here, passing an empty string returns a False, as a failure to convert something that is empty. 

Python3

test_dict = {}

print["The original dictionary : " + str[test_dict]]

res = not bool[test_dict]

print["Is dictionary empty ? : " + str[res]]

Output :

The original dictionary : {}
Is dictionary empty ? : True

Check if a Dictionary is Empty using not operator 

This task can also be performed using the not operator that checks for a dictionary existence, this evaluates to True if any key in the dictionary is not found. 

Python3

test_dict = {}

print["The original dictionary : " + str[test_dict]]

res = not test_dict

print["Is dictionary empty ? : " + str[res]]

Output:

The original dictionary : {}
Is dictionary empty ? : True

Check if a Dictionary is Empty using len[]

Here, we are using the Python len[] to check if the dictionary is empty or not.

Python3

test_dict = {}

print["The original dictionary : " + str[test_dict]]

res = len[myDict] == 0

print["Is dictionary empty ? : " + str[res]]

Output:

The original dictionary : {}
Is dictionary empty ? : True

Check if a Dictionary is Empty using the Equality Operator

Here, we are comparing the dictionary with values with an empty dictionary to check if the dictionary is empty or not.

Python3

myDict = {1: 'Hello', 2: 'World' }

test_dict = {}

print["The original dictionary : " + str[test_dict]]

res = test_dict == myDict

print["Is dictionary empty ? : " + str[res]]

Output:

The original dictionary : {}
Is dictionary empty ? : False

I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays ONLINE without anything except of display the message. Any ideas why ?

def isEmpty[self, dictionary]:
    for element in dictionary:
        if element:
            return True
        return False

def onMessage[self, socket, message]:
    if self.isEmpty[self.users] == False:
        socket.send["Nobody is online, please use REGISTER command" \
                 " in order to register into the server"]
    else:
        socket.send["ONLINE " + ' ' .join[self.users.keys[]]]    

asked Apr 20, 2014 at 1:29

6

Empty dictionaries evaluate to False in Python:

>>> dct = {}
>>> bool[dct]
False
>>> not dct
True
>>>

Thus, your isEmpty function is unnecessary. All you need to do is:

def onMessage[self, socket, message]:
    if not self.users:
        socket.send["Nobody is online, please use REGISTER command" \
                    " in order to register into the server"]
    else:
        socket.send["ONLINE " + ' ' .join[self.users.keys[]]]

answered Apr 20, 2014 at 1:31

6

Here are three ways you can check if dict is empty. I prefer using the first way only though. The other two ways are way too wordy.

test_dict = {}

if not test_dict:
    print "Dict is Empty"


if not bool[test_dict]:
    print "Dict is Empty"


if len[test_dict] == 0:
    print "Dict is Empty"

answered Apr 20, 2014 at 4:29

doubleodoubleo

4,1794 gold badges15 silver badges19 bronze badges

4

dict = {}
print[len[dict.keys[]]]

if length is zero means that dict is empty

Bram Vanroy

25.7k23 gold badges125 silver badges222 bronze badges

answered Dec 16, 2016 at 10:00

3

Simple ways to check an empty dict are below:

        a= {}

    1. if a == {}:
           print ['empty dict']
    2. if not a:
           print ['empty dict']

Although method 1st is more strict as when a = None, method 1 will provide correct result but method 2 will give an incorrect result.

answered Dec 11, 2018 at 10:11

A dictionary can be automatically cast to boolean which evaluates to False for empty dictionary and True for non-empty dictionary.

if myDictionary: non_empty_clause[]
else: empty_clause[]

If this looks too idiomatic, you can also test len[myDictionary] for zero, or set[myDictionary.keys[]] for an empty set, or simply test for equality with {}.

The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.

  1. The return False statement is indented one level too deep. It should be outside the for loop and at the same level as the for statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives.
  2. If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives.
  3. Let us say you correct the indentation of the return False statement and bring it outside the for loop. Then what you get is the boolean OR of all the keys, or False if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.

myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', []:'Empty tuple'}

answered Jan 14, 2019 at 10:25

DellaDella

1,0752 gold badges14 silver badges29 bronze badges

One Way:

 len[given_dic_obj] 

returns 0 if there is no element else return the size of the dictionary.

Second Way:

bool[given_dic_object]

returns False if the dictionary is empty else return True

Andy

8201 gold badge8 silver badges21 bronze badges

answered Dec 19, 2021 at 23:24

Arpan SainiArpan Saini

3,65134 silver badges44 bronze badges

3

You can also use get[]. Initially I believed it to only check if key existed.

>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool[d.get['c']]
False
>>> d['c']['e']=1
>>> bool[d.get['c']]
True

What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.

answered Nov 16, 2017 at 12:49

MortenBMortenB

2,10323 silver badges31 bronze badges

test_dict = {}
if not test_dict.keys[]:
    print "Dict is Empty"

answered Sep 3, 2020 at 13:33

NotTooTechyNotTooTechy

3844 silver badges8 bronze badges

use 'any'

dict = {}

if any[dict] :

     # true
     # dictionary is not empty 

else :

     # false 
     # dictionary is empty

answered May 13, 2016 at 12:39

2

Chủ Đề