python - How can I properly copy nested dictionary objects? -
i'm working on project python 2.7 have "complex" dictionary structure, , trying this:
generic_dict = { 'user': {'created': {}, 'modified': {}, 'errors': {}}, 'usermon': {'created': {}, 'modified': {}, 'ignored': {}, 'errors': {}} log_data = { 'esp': generic_dict, 'por': generic_dict, 'sui': generic_dict, 'ben': generic_dict, 'mex': generic_dict, 'arg': generic_dict, }
i trying use generic dict avoid repeating code have problem if this, when modify of country dicts (esp, ben, por) modifying @ same time.
let's assume dictionary empty , this
log_data['esp']['user']['created']['today'] = 'asdasdasda'
all other dicts have same value generic_dict same of them.
print log_data['ben']['user']['created'] output: {'today': 'asdasdasda'} print log_data['ben']['user']['created'] output: {'today': 'asdasdasda'}
i understand what's happening don't know how avoid that
- which best way copy nested dictionary objects ?
you can use copy.deepcopy
create new copy of generic_dict
object, this
from copy import deepcopy log_data = { 'esp': deepcopy(generic_dict), 'por': deepcopy(generic_dict), 'sui': deepcopy(generic_dict), 'ben': deepcopy(generic_dict), 'mex': deepcopy(generic_dict), 'arg': deepcopy(generic_dict), }
otherwise, can have constructor function, this
def generic_dict(): return {'user': {'created': {}, 'modified': {}, 'errors': {}}, 'usermon': {'created': {}, 'modified':{}, 'ignored': {}, 'errors': {}}}
and call create new dictionary object every time, this
log_data = { 'esp': generic_dict(), 'por': generic_dict(), 'sui': generic_dict(), 'ben': generic_dict(), 'mex': generic_dict(), 'arg': generic_dict(), }
Comments
Post a Comment