Accessing dict keys like an attribute?

前端 未结 27 2111
南笙
南笙 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 04:50

    This doesn't address the original question, but should be useful for people that, like me, end up here when looking for a lib that provides this functionality.

    Addict it's a great lib for this: https://github.com/mewwts/addict it takes care of many concerns mentioned in previous answers.

    An example from the docs:

    body = {
        'query': {
            'filtered': {
                'query': {
                    'match': {'description': 'addictive'}
                },
                'filter': {
                    'term': {'created_by': 'Mats'}
                }
            }
        }
    }
    

    With addict:

    from addict import Dict
    body = Dict()
    body.query.filtered.query.match.description = 'addictive'
    body.query.filtered.filter.term.created_by = 'Mats'
    

提交回复
热议问题