Python tip: default dict

Sometimes you need to initialize dictionary before you use it, for this reason you can use dict() subclass defaultdict(). This is how you would do it normally.

# counter for cars by vendor
cars = dict()
if 'ferrari' not in cars:
cars['ferrari'] = 1
else:
cars['ferrari'] += 1

but with default dict this scenario is far easier

# counter for cars by vendor
from collections import defaultdict
cars = defaultdict(int)
cars['ferrari'] += 1

Always remember that defaultdict takes as parameter callable (function) not default value.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Martin Koníček
Martin Koníček

Written by Martin Koníček

AWS and Python developer and Linux enthusiastic.

No responses yet

Write a response