sam
sam

Reputation: 494

How to check an empty dictionary?

I have the following code. I want to write a condition if there is an empty dictionary.

 belongingsList = []
    for item, count in self.belongings.items():
        if count >= 1:
            belongingsList.append(item)


    return belongingsList

I want to return an empty list if the dictionary is empty

Upvotes: 2

Views: 3147

Answers (2)

Green Cell
Green Cell

Reputation: 4777

You just need a simple check at the beginning to see if it's empty, then return an empty list if it is. You can also use a list comprehension to simplify it so it's not so many lines:

def yourFunction():
    # Return an empty list if the dict is empty.
    if not self.belongings:
        return []

    # Can use a list comprehension to simplify code.    
    return [item for item, count in self.belongings.items() if count >= 1]

Honestly you don't even need the beginning check since if it's an empty dict then the list comprehension will return you an empty list like you want:

def yourFunction():   
    return [item for item, count in self.belongings.items() if count >= 1]

Upvotes: 3

Andreas
Andreas

Reputation: 2521

You could check by using len() function, which when applied to dictionary object, will checks for the number of key-value pairs in the dictionary

belongingList = []
if len(belongings) == 0: # check if the dictionary is empty
    return belongingList
else:
    for item, count in self.belongings.items():
        if count >= 1:
            belongingsList.append(item)
    return belongingList

Another way to do it

belongingsList = []

if len(belongings) > 0: # check if the dictionary is not empty
    for item, count in self.belongings.items():
        if count >= 1:
            belongingsList.append(item)

return belongingsList

Upvotes: 3

Related Questions