Check if dictionary empty with == {}

Laurent Pointal laurent.pointal at free.fr
Thu Aug 20 11:56:50 EDT 2015


Anton wrote:

> Probably a silly question.
> Let's say I have a dictionary mydict and I need to test if a dictionary is
> empty.
> 
> I would use
> 
> if not mydict:
>     """do something"""
> 
> But I just came across a line of code like:
> 
> if mydict == {}:
>     """do something"""
> 
> which seems odd to me, but maybe there is a valid use case, thus I decided
> to ask the community.
> 
> Thanks.

You can also use:

if len(mydict) == 0:
    "do something"

The form 'if not mydict:' is AMA the more pythonic, but it may be a source 
of question for beginners (what is the boolean meaning of a dictionnary…).

A+
Laurent.




More information about the Python-list mailing list