Home > Article > Backend Development > How can I convert a nested Python dictionary into an object-like structure for attribute-based data retrieval?
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
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
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!