Home  >  Article  >  Backend Development  >  How to Access Nested Python Dictionaries Like Objects?

How to Access Nested Python Dictionaries Like Objects?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 04:51:03706browse

How to Access Nested Python Dictionaries Like Objects?

How to Transform a Nested Python Dictionary into an Object

For convenience, it is desirable to access data using attribute access on dictionaries containing nested dictionaries and lists, akin to JavaScript's object syntax. For instance:

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

This data should be accessible as follows:

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

Crafting such a function necessitates recursion. Here's an approach to achieve object-like functionality for dictionaries:

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

Usage:

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

Alternative Solution: Namedtuples

For Python versions 2.6 and later, consider utilizing the namedtuple data structure:

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

Now you have a named tuple that behaves like an object, with attribute access for its fields. This provides a concise and highly readable solution.

The above is the detailed content of How to Access Nested Python Dictionaries Like Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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