Check if dictionary empty with == {}
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Aug 19 23:16:52 EDT 2015
On Thursday 20 August 2015 08:57, 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.
It's neither good code or bad code. It looks like something a beginner or
casual Python user (e.g. a sys admin) might have written, but that isn't
necessarily bad. It's no more wrong than writing `if x == 0` to test for an
"empty" number (or "nothing", in the numeric sense).
Pros:
+ It's pretty short and explicit.
+ It allows for duck-typing: if some de facto mapping object wants to
support the dict API without inheriting from dict, it can.
+ Even a beginner can understand it: "does mydict equal an
empty dict?"
Cons:
- It looks a bit Python 1.5-ish. People used to more modern
idioms may have an (unjustified, in my opinion) "WTF" moment
when looking at it.
- It *might* be a bit slow, since it takes time to create an
empty dict; on the other hand, it also takes time to call
isinstance(), so if you care about this, I want to see your
profiling results and benchmarks.
Actually, it's not a bit slow, it's *significantly* faster than an
isinstance check:
steve at runes:~$ python2.7 -m timeit -s "mydict = {1:2}" \
> "if mydict == {}: pass"
10000000 loops, best of 3: 0.0872 usec per loop
steve at runes:~$ python2.7 -m timeit -s "mydict = {1:2}" \
> "if isinstance(mydict, dict) and not mydict: pass"
1000000 loops, best of 3: 0.257 usec per loop
So maybe it's a micro-optimization?
TL;DR
There's nothing wrong with it. It is ever-so-subtly different from the
various alternatives, so if you change it, don't be surprised if you break
something.
--
Steven
More information about the Python-list
mailing list