Merging two dictionaries

Douglas Garstang doug.garstang at gmail.com
Mon Aug 2 01:09:23 EDT 2010


Anyone,

I have the two dictionaries below. How can I merge them, such that:

1. The cluster dictionary contains the additional elements from the
default dictionary.
2. Nothing is removed from the cluster dictionary.

The idea here is that the two dictionaries are read from different
files where, if the value isn't found in the cluster dictionary, it's
pulled from the default one, and I can have a new dictionary
reflecting this. The update() method on dictionaries doesn't seem to
work. The resulting dictionary always seems to be the one passed as a
parameter.

default = {
    'cluster': {
        'platform': {
            'elements': {
                'data_sources': {
                    'elements': {
                        'db_min_pool_size': 10
                    },
                },
            },
        },
    }
}

cluster = {
    'cluster': {
        'name': 'Customer 1',
        'description': 'Production',
        'environment': 'production',
        'platform': {
            'elements': {
                'data_source': {
                    'elements': {
                        'username': 'username',
                        'password': 'password'
                    },
                },
            },
        },
    }
}

The resulting dictionary would therefore look like this:

new_dict = {
    'cluster': {
        'name': 'Customer 1',
        'description': 'Production',
        'environment': 'production',
        'platform': {
            'elements': {
                'data_source': {
                    'elements': {
                        'username': 'username',
                        'password': 'password',
                        'db_min_pool_size': 10 # This was added from
the default.
                    },
                },
            },
        },
    }
}


Thanks,
Doug.

-- 
Regards,

Douglas Garstang
http://www.linkedin.com/in/garstang
Email: doug.garstang at gmail.com
Cell: +1-805-340-5627



More information about the Python-list mailing list