Accessing dict keys like an attribute?

前端 未结 27 2157
南笙
南笙 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条回答
  •  旧时难觅i
    2020-11-22 05:12

    As noted by Doug there's a Bunch package which you can use to achieve the obj.key functionality. Actually there's a newer version called

    NeoBunch

    It has though a great feature converting your dict to a NeoBunch object through its neobunchify function. I use Mako templates a lot and passing data as NeoBunch objects makes them far more readable, so if you happen to end up using a normal dict in your Python program but want the dot notation in a Mako template you can use it that way:

    from mako.template import Template
    from neobunch import neobunchify
    
    mako_template = Template(filename='mako.tmpl', strict_undefined=True)
    data = {'tmpl_data': [{'key1': 'value1', 'key2': 'value2'}]}
    with open('out.txt', 'w') as out_file:
        out_file.write(mako_template.render(**neobunchify(data)))
    

    And the Mako template could look like:

    % for d in tmpl_data:
    Column1     Column2
    ${d.key1}   ${d.key2}
    % endfor
    

提交回复
热议问题