Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- my_dict = {}
- default_value = {'surname': '', 'age': 0}
- # get info about john, or a default dict
- item = my_dict.get('john', default_value)
- # edit the data
- item[surname] = 'smith'
- item[age] = 68
- my_dict['john'] = item
- >>> default_value
- {'age': 68, 'surname': 'smith'}
- item = my_dict.get('john', {'surname': '', 'age': 0})
- item = my_dict.get('john', default_value.copy())
- def my_dict_get(key):
- try:
- item = my_dict[key]
- except KeyError:
- item = default_value.copy()
- my_dict.get('john', default_value.copy())
- from collections import defaultdict
- def factory():
- return {'surname': '', 'age': 0}
- my_dict = defaultdict(factory)
- my_dict['john']
- item = my_dict.get('john', default_value.copy())
- item = my_dict['john'] if 'john' in my_dict else default_value.copy()
- item = my_dict.get('john')
- if item is None:
- item = default_value.copy()
- def my_dict_get():
- try:
- item = my_dict['key']
- except KeyError:
- item = default_value.copy()
- # key present: 0.4179
- # key absent: 3.3799
- def my_dict_get():
- item = my_dict.get('key')
- if item is None:
- item = default_value.copy()
- # key present: 0.57189
- # key absent: 0.96691
- def my_dict_get():
- item = my_dict['key'] if 'key' in my_dict else default_value.copy()
- # key present: 0.39721
- # key absent: 0.43474
- def my_dict_get():
- item = my_dict.get('key', default_value.copy())
- # key present: 0.52303 (this may be lower than it should be as the dictionary I used was one element)
- # key absent: 0.66045
- item = my_dict.get('john')
- if item is None:
- item = default_dict.copy()
- try:
- return my_dict['john']
- except KeyError:
- return {'surname': '', 'age': 0}
- import collections
- def default_factory():
- return {'surname': '', 'age': 0}
- my_dict = collections.defaultdict(default_factory)
Add Comment
Please, Sign In to add comment