Quantcast
Channel: How to use a dot "." to access members of dictionary? - Stack Overflow
Viewing all articles
Browse latest Browse all 40

Answer by deepak for How to use a dot "." to access members of dictionary?

$
0
0

This solution is a refinement upon the one offered by epool to address the requirement of the OP to access nested dicts in a consistent manner. The solution by epool did not allow for accessing nested dicts.

class YAMLobj(dict):    def __init__(self, args):        super(YAMLobj, self).__init__(args)        if isinstance(args, dict):            for k, v in args.iteritems():                if not isinstance(v, dict):                    self[k] = v                else:                    self.__setattr__(k, YAMLobj(v))    def __getattr__(self, attr):        return self.get(attr)    def __setattr__(self, key, value):        self.__setitem__(key, value)    def __setitem__(self, key, value):        super(YAMLobj, self).__setitem__(key, value)        self.__dict__.update({key: value})    def __delattr__(self, item):        self.__delitem__(item)    def __delitem__(self, key):        super(YAMLobj, self).__delitem__(key)        del self.__dict__[key]

With this class, one can now do something like: A.B.C.D.


Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>