[PYTHON] Memo that refers to dictionary values as attributes (reinventing the wheel)

AttrDict is more convenient, but for those who want to use it for a while but don't want to install it

Definition

class Dict(dict): pass
Dict.__getattr__ = lambda s, k: s.get(k)

When using

a = Dict(a=0, b=Dict(c=1, d=2))
(a.a, a.b.c, a["a"], a["b"]["c"])

I want to define it a little more firmly

class Dict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    
    def __getattr__(self, key):
        return self.get(key)
    
    def __getstate__(self):
        return self.__dict__
    
    def __setstate__(self, dict_):
        self.__dict__ = dict_

a = Dict(a=0, b=Dict(c=1, d=2))
(a.a, a.b.c, a["a"], a["b"]["c"], pickle.loads(pickle.dumps(a)))

__getstate__, __setstate__Is a pickle measure. You have to use pickle.

Extra edition

I wrote it on One Liner. Kaketadake

globals().update({"D": type("D", (dict,), {"__getattr__": lambda s, k: s.get(k)})}); D(a=1, b=D(c=2, d=3)).b.c

Recommended Posts

Memo that refers to dictionary values as attributes (reinventing the wheel)
How to get all the keys and values in the dictionary
Normalize the file that converted Excel to csv as it is.