티스토리 뷰

개발/파이썬

빈 딕셔너리인지 확인하기

맨날치킨 2022. 12. 29. 11:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

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

Python: '딕셔너리'가 비어 있는지 확인하는 것이 작동하지 않는 것 같습니다.

 문제 내용 

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()))    

 

 

 높은 점수를 받은 Solution 

Empty dictionaries evaluate to False in Python:

Python에서 빈 딕셔너리는 False로 평가됩니다.
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>

 

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

따라서 isEmpty 함수는 필요하지 않습니다. 필요한 것은 다음과 같습니다.
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()))

 

 

 가장 최근 달린 Solution 

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

딕셔너리를 자동으로 부울로 캐스팅하여 빈 딕셔너리의 경우 False로, 비어 있지 않은 딕셔너리의 경우 True로 평가할 수 있습니다.
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 {}.

이것이 너무 관용적으로 보이면 len(myDictionary)에서 0을 테스트하거나 set(myDictionary.keys())에서 빈 세트를 테스트하거나 단순히 {}와 같은지 테스트할 수 있습니다.

 

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

isEmpty 함수는 불필요할 뿐만 아니라 당신의 구현에는 제가 가장 많이 발견할 수 있는 여러 문제가 있습니다.

 

  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.
1. Return False 문이 너무 깊이 들여쓰기되었습니다. for 루프 밖에 있고 for 문과 동일한 수준이어야 합니다. 따라서 키가 있는 경우 코드는 임의로 선택한 하나의 키만 처리합니다. 키가 없으면 함수는 없음을 반환하고, 이는 부울 False로 캐스팅됩니다. 앗! 모든 빈 딕셔너리는 거짓 음성으로 분류됩니다.
2. 딕셔너리가 비어 있지 않으면 코드는 하나의 키만 처리하고 해당 값을 부울로 캐스트하여 반환합니다. 호출할 때마다 동일한 키가 평가된다고 가정할 수도 없습니다. 따라서 잘못된 긍정이 있을 것입니다.
3. 리턴 False 문의 들여쓰기를 수정하여 for 루프 외부로 가져온다고 가정해 보겠습니다. 그러면 모든 키의 부울 OR이 표시되고 딕셔너리가 비어 있으면 False가 표시됩니다. 여전히 당신은 잘못된 긍정과 잘못된 부정을 갖게 될 것이다. 증거를 찾기 위해 다음 딕셔너리와 비교하여 수정하고 테스트하십시오.

 

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

 

 

출처 : https://stackoverflow.com/questions/23177439/python-checking-if-a-dictionary-is-empty-doesnt-seem-to-work

반응형
댓글
공지사항
최근에 올라온 글