Guest User

Untitled

a guest
Jul 20th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. my_dict = {}
  2. default_value = {'surname': '', 'age': 0}
  3.  
  4. # get info about john, or a default dict
  5. item = my_dict.get('john', default_value)
  6.  
  7. # edit the data
  8. item[surname] = 'smith'
  9. item[age] = 68
  10.  
  11. my_dict['john'] = item
  12.  
  13. >>> default_value
  14. {'age': 68, 'surname': 'smith'}
  15.  
  16. item = my_dict.get('john', {'surname': '', 'age': 0})
  17.  
  18. item = my_dict.get('john', default_value.copy())
  19.  
  20. def my_dict_get(key):
  21. try:
  22. item = my_dict[key]
  23. except KeyError:
  24. item = default_value.copy()
  25.  
  26. my_dict.get('john', default_value.copy())
  27.  
  28. from collections import defaultdict
  29.  
  30. def factory():
  31. return {'surname': '', 'age': 0}
  32.  
  33. my_dict = defaultdict(factory)
  34.  
  35. my_dict['john']
  36.  
  37. item = my_dict.get('john', default_value.copy())
  38.  
  39. item = my_dict['john'] if 'john' in my_dict else default_value.copy()
  40.  
  41. item = my_dict.get('john')
  42. if item is None:
  43. item = default_value.copy()
  44.  
  45. def my_dict_get():
  46. try:
  47. item = my_dict['key']
  48. except KeyError:
  49. item = default_value.copy()
  50.  
  51. # key present: 0.4179
  52. # key absent: 3.3799
  53.  
  54. def my_dict_get():
  55. item = my_dict.get('key')
  56. if item is None:
  57. item = default_value.copy()
  58.  
  59. # key present: 0.57189
  60. # key absent: 0.96691
  61.  
  62. def my_dict_get():
  63. item = my_dict['key'] if 'key' in my_dict else default_value.copy()
  64.  
  65. # key present: 0.39721
  66. # key absent: 0.43474
  67.  
  68. def my_dict_get():
  69. item = my_dict.get('key', default_value.copy())
  70.  
  71. # key present: 0.52303 (this may be lower than it should be as the dictionary I used was one element)
  72. # key absent: 0.66045
  73.  
  74. item = my_dict.get('john')
  75. if item is None:
  76. item = default_dict.copy()
  77.  
  78. try:
  79. return my_dict['john']
  80. except KeyError:
  81. return {'surname': '', 'age': 0}
  82.  
  83. import collections
  84.  
  85. def default_factory():
  86. return {'surname': '', 'age': 0}
  87.  
  88. my_dict = collections.defaultdict(default_factory)
Add Comment
Please, Sign In to add comment