What’s the proper way to check if a dictionary is empty in Python?

I’m trying to determine if a dictionary in Python is empty, but my current approach isn’t working as expected. I have some code that iterates over the dictionary, but it seems to skip things or behave incorrectly, sometimes it just displays “ONLINE” even when no users are registered.

Here’s a simplified version of what I’m doing:

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"
                    " to register into the server")
    else:
        socket.send("ONLINE " + ' '.join(self.users.keys()))

I’m looking for a cleaner, reliable way to check if dictionary is empty python, so I can accurately handle the case where no entries exist.

What’s the recommended approach for checking whether a dictionary has any items?

I used to iterate over dictionaries too, like you did, but that often caused logic errors. Another approach is to check the length:

if len(my_dict) == 0:
    print("No entries")

This is explicit and also very clear for newcomers.

From my experience in server-side Python code, the if not dict approach is both idiomatic and efficient. It avoids unnecessary iteration and works in any situation, even if you’re working with dynamic or nested dictionaries.

I’ve run into the same confusion before. The simplest and Pythonic way is just to check the dictionary directly in a conditional. Empty dictionaries are “falsy” in Python, so you can do:

if not my_dict:
    print("Dictionary is empty")
else:
    print("Dictionary has values")

No loops needed, and it’s very readable.