Advertisement
Guest User

Untitled

a guest
Oct 21st, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. a = {'one':1,'two':2}
  2. print a['three']
  3.  
  4. import collections
  5. a = collections.defaultdict(lambda: 3)
  6. a.update({'one':1,'two':2})
  7. print a['three']
  8.  
  9. >>> import sys
  10. >>> a = collections.defaultdict(lambda: 'blah')
  11. >>> print len(a), sys.getsizeof(a)
  12. 0 140
  13. >>> for i in xrange(99): _ = a[i]
  14. ...
  15. >>> print len(a), sys.getsizeof(a)
  16. 99 6284
  17.  
  18. >>> class mydict(dict):
  19. ... def __missing__(self, key): return 3
  20. ...
  21. >>> a = mydict()
  22. >>> print len(a), sys.getsizeof(a)
  23. 0 140
  24. >>> for i in xrange(99): _ = a[i]
  25. ...
  26. >>> print len(a), sys.getsizeof(a)
  27. 0 140
  28.  
  29. $ python -mtimeit -s'import collections; a=collections.defaultdict(int); r=xrange(99)' 'for i in r: _=a[i]'
  30. 100000 loops, best of 3: 14.9 usec per loop
  31.  
  32. $ python -mtimeit -s'class mydict(dict):
  33. > def __missing__(self, key): return 0
  34. > ' -s'a=mydict(); r=xrange(99)' 'for i in r: _=a[i]'
  35. 10000 loops, best of 3: 92.9 usec per loop
  36.  
  37. >>> class forgiving_dict(dict):
  38. ... def __missing__(self, key):
  39. ... return 3
  40. ...
  41. >>> a = forgiving_dict()
  42. >>> a.update({'one':1,'two':2})
  43. >>> print a['three']
  44. 3
  45.  
  46. >>> print a
  47. {'two': 2, 'one': 1}
  48.  
  49. from collections import defaultdict
  50. def default(): return 'Default Value'
  51. d = defaultdict(default)
  52. print(d['?'])
  53.  
  54. collection = {}
  55. for elem in mylist:
  56. key = key_from_elem(elem)
  57. collection.setdefault(key, []).append(elem)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement