覆盖 {...} 符号,所以我得到一个 OrderedDict() 而不是 dict()? [英] Override the {...} notation so i get an OrderedDict() instead of a dict()?

查看:31
本文介绍了覆盖 {...} 符号,所以我得到一个 OrderedDict() 而不是 dict()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:Python 3.7+ 保证 dicts 保留插入顺序

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

我想使用像配置文件一样的 .py 文件.因此,使用 {...} 符号我可以创建一个使用字符串作为键的字典,但定义顺序在标准 python 字典中丢失了.

I want to use a .py file like a config file. So using the {...} notation I can create a dictionary using strings as keys but the definition order is lost in a standard python dictionary.

我的问题:是否可以覆盖 {...} 符号,以便我得到 OrderedDict() 而不是 dict()?

My question: is it possible to override the {...} notation so that I get an OrderedDict() instead of a dict()?

我希望用 OrderedDict (dict = OrderedDict) 简单地覆盖 dict 构造函数会起作用,但它没有.

I was hoping that simply overriding dict constructor with OrderedDict (dict = OrderedDict) would work, but it doesn't.

例如:

dict = OrderedDict
dictname = {
   'B key': 'value1',
   'A key': 'value2',
   'C key': 'value3'
   }

print dictname.items()

输出:

[('B key', 'value1'), ('A key', 'value2'), ('C key', 'value3')]

推荐答案

这是一个几乎可以为您提供所需语法的技巧:

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"
]

其他人独立发现了这一点,并发布了odictliteral 包提供了更彻底的实现 - 改用该包

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

这篇关于覆盖 {...} 符号,所以我得到一个 OrderedDict() 而不是 dict()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆