How can I properly copy nested dictionary objects?
Question: 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 ? 


Answer: You can use
[`copy.deepcopy`](https://docs.python.org/2/library/copy.html#copy.deepcopy)
to create a new copy of the `generic_dict` object, like 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, you can have a constructor function, like this

    
    
    def generic_dict():
        return {'user': {'created': {}, 'modified': {}, 'errors': {}},
                'usermon': {'created': {}, 'modified':{}, 'ignored': {}, 'errors': {}}}
    

And then call it to create a new dictionary object every time, like this

    
    
    log_data = {
        'esp': generic_dict(),
        'por': generic_dict(),
        'sui': generic_dict(),
        'ben': generic_dict(),
        'mex': generic_dict(),
        'arg': generic_dict(),
    }
    

