Convert nested Python dict to object?

后端 未结 30 2600
时光取名叫无心
时光取名叫无心 2020-11-22 09:28

I\'m searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

30条回答
  •  借酒劲吻你
    2020-11-22 10:13

    I know there's already a lot of answers here already and I'm late to the party but this method will recursively and 'in place' convert a dictionary to an object-like structure... Works in 3.x.x

    def dictToObject(d):
        for k,v in d.items():
            if isinstance(v, dict):
                d[k] = dictToObject(v)
        return namedtuple('object', d.keys())(*d.values())
    
    # Dictionary created from JSON file
    d = {
        'primaryKey': 'id', 
        'metadata': 
            {
                'rows': 0, 
                'lastID': 0
            }, 
        'columns': 
            {
                'col2': {
                    'dataType': 'string', 
                    'name': 'addressLine1'
                }, 
                'col1': {
                    'datatype': 'string', 
                    'name': 'postcode'
                }, 
                'col3': {
                    'dataType': 'string', 
                    'name': 'addressLine2'
                }, 
                'col0': {
                    'datatype': 'integer', 
                    'name': 'id'
                }, 
                'col4': {
                    'dataType': 'string', 
                    'name': 'contactNumber'
                }
            }, 
            'secondaryKeys': {}
    }
    
    d1 = dictToObject(d)
    d1.columns.col1 # == object(datatype='string', name='postcode')
    d1.metadata.rows # == 0
    

提交回复
热议问题