How can I convert a nested Python dictionary into an object-like structure for attribute-based data retrieval?

DDD
Release: 2024-11-11 08:50:02
Original
1000 people have browsed it

How can I convert a nested Python dictionary into an object-like structure for attribute-based data retrieval?

Converting Nested Python Dicts to Objects

Accessor methods offer a convenient way to retrieve data from complex data structures, allowing for intuitive object-oriented navigation. However, Python's native dictionaries inherently lack this functionality.

Problem: How can we convert a nested Python dictionary into an object-like structure, enabling attribute-based data retrieval?

Answer:

Using Namedtuples (Python 2.6 and Later)

For newer versions of Python (2.6 and onward), namedtuples provide an elegant solution. These represent immutable custom data types with named fields:

from collections import namedtuple

MyStruct = namedtuple('MyStruct', 'a b d')
s = MyStruct(a=1, b={'c': 2}, d=['hi'])

print(s.a, s.b['c'], s.d[0])
# Output: 1 2 hi
Copy after login

Using a Custom Struct Class

Alternatively, you can create a custom Struct class that mimics the behavior of objects:

class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)

args = {'a': 1, 'b': 2}
s = Struct(**args)

print(s.a, s.b)
# Output: 1 2
Copy after login

The above is the detailed content of How can I convert a nested Python dictionary into an object-like structure for attribute-based data retrieval?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template