Convert nested Python dict to object?

后端 未结 30 1927
时光取名叫无心
时光取名叫无心 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:16

    Typically you want to mirror dict hierarchy into your object but not list or tuples which are typically at lowest level. So this is how I did this:

    class defDictToObject(object):
    
        def __init__(self, myDict):
            for key, value in myDict.items():
                if type(value) == dict:
                    setattr(self, key, defDictToObject(value))
                else:
                    setattr(self, key, value)
    

    So we do:

    myDict = { 'a': 1,
               'b': { 
                  'b1': {'x': 1,
                        'y': 2} },
               'c': ['hi', 'bar'] 
             }
    

    and get:

    x.b.b1.x 1

    x.c ['hi', 'bar']

提交回复
热议问题