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

How to Access Nested Python Dictionaries Like Objects?

Mary-Kate Olsen
Release: 2024-11-11 04:51:03
Original
799 people have browsed it

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"}]}
Copy after login

This data should be accessible as follows:

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

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)
Copy after login

Usage:

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

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'])
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template