default dict in python

linkaiyi
Follow

use defaultdict from collections to give default value to new key

>>> from collections import defaultdict

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

default with int 2 instead of 0

area_number_dict = defaultdict(lambda: 2)
Object has 0 attachments

Was this article helpful?

This article is viewed 9 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support