Default dictionary
1 2 >> d = DefaultDict(0) 3 >> d[key] += 1 # no need to use d.get or d.setdefault 4 5 >> d = DefaultDict([]) # similarly with list value 6 >> d[key].append(item)
See the implementation by Peter Norvig (of AI & Google fame)
here
DZone Snippets > korakot > default
12729 users tagging and storing useful source code snippets
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Korakot Chaovavanich http://korakot.stumbleupon.com
1 2 >> d = DefaultDict(0) 3 >> d[key] += 1 # no need to use d.get or d.setdefault 4 5 >> d = DefaultDict([]) # similarly with list value 6 >> d[key].append(item)
1 2 >>> s = 'a;jfkd;aflhakfhaskfjalghlakfhfnkjafyksd' 3 >>> cnt = {} 4 >>> for c in s: 5 cnt[c] = cnt.get(c,0) + 1 6 7 >>> print cnt 8 {'a': 7, 'd': 2, 'g': 1, 'f': 7, 'h': 4, 'k': 6, 'j': 3, 'l': 3, 'n': 1, 's': 2, 'y': 1, ';': 2}
1 cnt[c] += 1