Python dict to object
Python objects are actually dicts, so it is fairly simple to represent a dict structure as an object. I find this useful when I have a configuration-like structures with multiple levels of nesting. It is far more easier to use such structure as config.x.y.z
than config['x']['y']['z']
.
The code would look like this:
class DictToObject(object):
def __init__(self, dictionary):
def _traverse(key, element):
if isinstance(element, dict):
return key, DictToObject(element)
else:
return key, element
objd = dict(_traverse(k, v) for k, v in dictionary.iteritems())
self.__dict__.update(objd)
self.__dict__.update
will update the object's internal dict representation with the supplied new structure and the recursive call of DictToObject
in _traverse
will take care of any nested dicts.
Example usage:
# let's pretend that you have loaded a json, yaml or other file
config_dict = {
'group1': {
'server1': {
'apps': ('nginx', 'mysql'),
'cpus': 4
},
'maintenance': True
},
'firewall_version': '1.2.3',
'python2.7': True
}
config = DictToObject(config_dict)
assert config.group1.server1.apps == ('nginx', 'mysql')
assert config.group1.maintenance
assert config.firewall_version == '1.2.3'
assert config.__dict__['python2.7'] # or use
assert config.__getattribute__('python2.7')
Complete version of the code could be found in this gist: Python dict to object
Written by Lachezar Yankov
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#