Python: Checking if a 'Dictionary' is empty doesn't seem to work

前端 未结 8 575
旧巷少年郎
旧巷少年郎 2020-12-02 04:27

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 m

8条回答
  •  一向
    一向 (楼主)
    2020-12-02 04:39

    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'}

提交回复
热议问题