Accessing dict keys like an attribute?

前端 未结 27 2140
南笙
南笙 2020-11-22 04:22

I find it more convenient to access dict keys as obj.foo instead of obj[\'foo\'], so I wrote this snippet:

class AttributeDict(dict         


        
27条回答
  •  心在旅途
    2020-11-22 05:04

    Let me post another implementation, which builds upon the answer of Kinvais, but integrates ideas from the AttributeDict proposed in http://databio.org/posts/python_AttributeDict.html.

    The advantage of this version is that it also works for nested dictionaries:

    class AttrDict(dict):
        """
        A class to convert a nested Dictionary into an object with key-values
        that are accessible using attribute notation (AttrDict.attribute) instead of
        key notation (Dict["key"]). This class recursively sets Dicts to objects,
        allowing you to recurse down nested dicts (like: AttrDict.attr.attr)
        """
    
        # Inspired by:
        # http://stackoverflow.com/a/14620633/1551810
        # http://databio.org/posts/python_AttributeDict.html
    
        def __init__(self, iterable, **kwargs):
            super(AttrDict, self).__init__(iterable, **kwargs)
            for key, value in iterable.items():
                if isinstance(value, dict):
                    self.__dict__[key] = AttrDict(value)
                else:
                    self.__dict__[key] = value
    

提交回复
热议问题