Accessing dict keys like an attribute?

前端 未结 27 2720
南笙
南笙 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:03

    This isn't a 'good' answer, but I thought this was nifty (it doesn't handle nested dicts in current form). Simply wrap your dict in a function:

    def make_funcdict(d=None, **kwargs)
        def funcdict(d=None, **kwargs):
            if d is not None:
                funcdict.__dict__.update(d)
            funcdict.__dict__.update(kwargs)
            return funcdict.__dict__
        funcdict(d, **kwargs)
        return funcdict
    

    Now you have slightly different syntax. To acces the dict items as attributes do f.key. To access the dict items (and other dict methods) in the usual manner do f()['key'] and we can conveniently update the dict by calling f with keyword arguments and/or a dictionary

    Example

    d = {'name':'Henry', 'age':31}
    d = make_funcdict(d)
    >>> for key in d():
    ...     print key
    ... 
    age
    name
    >>> print d.name
    ... Henry
    >>> print d.age
    ... 31
    >>> d({'Height':'5-11'}, Job='Carpenter')
    ... {'age': 31, 'name': 'Henry', 'Job': 'Carpenter', 'Height': '5-11'}
    

    And there it is. I'll be happy if anyone suggests benefits and drawbacks of this method.

提交回复
热议问题