[Python] How to convert a nested Python dict to object?

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    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:

    >>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}


    Should be accessible in this way:

    >>> x = dict2obj(d)
    >>> x.a
    1
    >>> x.b.c
    2
    >>> x.d[1].foo
    bar


    I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?

    Continue reading...

Compartilhe esta Página