프로그래밍 언어/Python
Python : 딕셔너리가 비어 있는지 확인하는 방법
Rateye
2021. 10. 8. 10:47
728x90
반응형
질문 : Python : '사전'이 비어 있는지 확인하는 것이 작동하지 않는 것 같습니다.
사전이 비어 있는지 확인하려고하는데 제대로 작동하지 않습니다. 그냥 건너 뛰고 메시지를 표시하는 것 외에는 아무것도없이 온라인으로 표시합니다. 이유는 무엇입니까?
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()))
답변
빈 사전은 Python False
로 평가됩니다.
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
따라서 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()))
출처 : https://stackoverflow.com/questions/23177439/python-checking-if-a-dictionary-is-empty-doesnt-seem-to-work
728x90
반응형