I'm working on a project with Python 2.7 where I have a "complex" dictionary structure, and I was trying to do something like 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 was trying to use the generic dict to avoid repeating code but I have a problem if I do like this, when I modify any of the country dicts (esp, ben, por) all are modifying at the same time.
Let's assume the dictionary is empty and I do this
log_data['esp']['user']['created']['today'] = 'asdasdasda'
all the other dicts now have the same value like generic_dict is the same all 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 but I don't know how to avoid that
- Which is the best way copy nested dictionary objects ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…