Convert nested Python dict to object?

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

    Let me explain a solution I almost used some time ago. But first, the reason I did not is illustrated by the fact that the following code:

    d = {'from': 1}
    x = dict2obj(d)
    
    print x.from
    

    gives this error:

      File "test.py", line 20
        print x.from == 1
                    ^
    SyntaxError: invalid syntax
    

    Because "from" is a Python keyword there are certain dictionary keys you cannot allow.


    Now my solution allows access to the dictionary items by using their names directly. But it also allows you to use "dictionary semantics". Here is the code with example usage:

    class dict2obj(dict):
        def __init__(self, dict_):
            super(dict2obj, self).__init__(dict_)
            for key in self:
                item = self[key]
                if isinstance(item, list):
                    for idx, it in enumerate(item):
                        if isinstance(it, dict):
                            item[idx] = dict2obj(it)
                elif isinstance(item, dict):
                    self[key] = dict2obj(item)
    
        def __getattr__(self, key):
            return self[key]
    
    d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
    
    x = dict2obj(d)
    
    assert x.a == x['a'] == 1
    assert x.b.c == x['b']['c'] == 2
    assert x.d[1].foo == x['d'][1]['foo'] == "bar"
    

提交回复
热议问题