Override the {…} notation so i get an OrderedDict() instead of a dict()?

后端 未结 7 654
野的像风
野的像风 2020-11-28 21:38

Update: dicts retaining insertion order is guaranteed for Python 3.7+

I want to use a .py file like a config file. So using the {.

相关标签:
7条回答
  • 2020-11-28 22:04

    Here's a hack that almost gives you the syntax you want:

    class _OrderedDictMaker(object):
        def __getitem__(self, keys):
            if not isinstance(keys, tuple):
                keys = (keys,)
            assert all(isinstance(key, slice) for key in keys)
    
            return OrderedDict([(k.start, k.stop) for k in keys])
    
    ordereddict = _OrderedDictMaker()
    
    from nastyhacks import ordereddict
    
    menu = ordereddict[
       "about" : "about",
       "login" : "login",
       'signup': "signup"
    ]
    

    Edit: Someone else discovered this independently, and has published the odictliteral package on PyPI that provides a slightly more thorough implementation - use that package instead

    0 讨论(0)
提交回复
热议问题