Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- a = {'one':1,'two':2}
- print a['three']
- import collections
- a = collections.defaultdict(lambda: 3)
- a.update({'one':1,'two':2})
- print a['three']
- >>> import sys
- >>> a = collections.defaultdict(lambda: 'blah')
- >>> print len(a), sys.getsizeof(a)
- 0 140
- >>> for i in xrange(99): _ = a[i]
- ...
- >>> print len(a), sys.getsizeof(a)
- 99 6284
- >>> class mydict(dict):
- ... def __missing__(self, key): return 3
- ...
- >>> a = mydict()
- >>> print len(a), sys.getsizeof(a)
- 0 140
- >>> for i in xrange(99): _ = a[i]
- ...
- >>> print len(a), sys.getsizeof(a)
- 0 140
- $ python -mtimeit -s'import collections; a=collections.defaultdict(int); r=xrange(99)' 'for i in r: _=a[i]'
- 100000 loops, best of 3: 14.9 usec per loop
- $ python -mtimeit -s'class mydict(dict):
- > def __missing__(self, key): return 0
- > ' -s'a=mydict(); r=xrange(99)' 'for i in r: _=a[i]'
- 10000 loops, best of 3: 92.9 usec per loop
- >>> class forgiving_dict(dict):
- ... def __missing__(self, key):
- ... return 3
- ...
- >>> a = forgiving_dict()
- >>> a.update({'one':1,'two':2})
- >>> print a['three']
- 3
- >>> print a
- {'two': 2, 'one': 1}
- from collections import defaultdict
- def default(): return 'Default Value'
- d = defaultdict(default)
- print(d['?'])
- collection = {}
- for elem in mylist:
- key = key_from_elem(elem)
- collection.setdefault(key, []).append(elem)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement