覆盖 {...} 符号,以便我得到 OrderedDict() 而不是 dict()?
更新:Python 3.7+ 保证保留插入顺序的字典
我想使用像配置文件一样的 .py 文件。
因此,使用 {...}
表示法,我可以使用字符串作为键创建一个字典,但定义顺序在标准 python 字典中丢失了。
我的问题:是否可以覆盖 {...}
表示法,以便我得到 OrderedDict()
而不是 dict()
?
我希望简单地用 OrderedDict (dict = OrderedDict
) 覆盖 dict 构造函数就可以工作,但事实并非如此。
例如:
dict = OrderedDict
dictname = {
'B key': 'value1',
'A key': 'value2',
'C key': 'value3'
}
print dictname.items()
输出:
[('B key', 'value1'), ('A key', 'value2'), ('C key', 'value3')]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一个几乎可以为您提供所需语法的黑客:
编辑:其他人独立发现了这一点,并发布了
odictliteral
包提供了稍微更彻底的实现 - 改用该包Here's a hack that almost gives you the syntax you want:
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要真正获得您所要求的内容,您必须摆弄文件的语法树。我认为这样做并不可取,但我无法抗拒尝试的诱惑。那么我们开始吧。
首先,我们创建一个带有函数
my_execfile()
的模块,其工作方式与内置execfile()
类似,只是显示所有出现的字典,例如{ 3: 4, "a": 2}
被显式调用dict()
构造函数替换,例如dict([(3, 4), ('a' , 2)])
。 (当然,我们可以通过调用collections.OrderedDict()
来直接替换它们,但我们不想太干扰。)代码如下:进行此修改后,我们可以通过覆盖
dict
来修改字典显示的行为。下面是一个示例:现在我们可以使用
my_execfile("test.py")
运行此文件,生成输出请注意,为了简单起见,上面的代码不涉及字典推导式,应该对其进行转换传递给 dict() 构造函数的生成器表达式。您需要将
visit_DictComp()
方法添加到DictDisplayTransformer
类中。鉴于上面的示例代码,这应该是简单的。再次强调,我不建议这种对语言语义的混乱。您查看过 ConfigParser 模块吗?
To literally get what you are asking for, you have to fiddle with the syntax tree of your file. I don't think it is advisable to do so, but I couldn't resist the temptation to try. So here we go.
First, we create a module with a function
my_execfile()
that works like the built-inexecfile()
, except that all occurrences of dictionary displays, e.g.{3: 4, "a": 2}
are replaced by explicit calls to thedict()
constructor, e.g.dict([(3, 4), ('a', 2)])
. (Of course we could directly replace them by calls tocollections.OrderedDict()
, but we don't want to be too intrusive.) Here's the code:With this modification in place, we can modify the behaviour of dictionary displays by overwriting
dict
. Here is an example:Now we can run this file using
my_execfile("test.py")
, yielding the outputNote that for simplicity, the above code doesn't touch dictionary comprehensions, which should be transformed to generator expressions passed to the
dict()
constructor. You'd need to add avisit_DictComp()
method to theDictDisplayTransformer
class. Given the above example code, this should be straight-forward.Again, I don't recommend this kind of messing around with the language semantics. Did you have a look into the
ConfigParser
module?OrderedDict
不是“标准 python 语法”,但是,一组有序的键值对(采用标准 python 语法)很简单:要显式获取
OrderedDict
:另一种选择,是对 dictname.items() 进行排序,如果这就是您所需要的:
OrderedDict
is not "standard python syntax", however, an ordered set of key-value pairs (in standard python syntax) is simply:To explicitly get an
OrderedDict
:Another alternative, is to sort
dictname.items()
, if that's all you need:从 python 3.6 开始,所有字典将按以下顺序排序默认。
插入顺序始终保留在新的
dict
实现中:从 python 3.6
**kwargs
顺序 [PEP468] 和类属性顺序 [PEP520] 被保留。新的紧凑、有序的字典实现 用于实现这两者的排序。As of python 3.6, all dictionaries will be ordered by default.
Insertion order is always preserved in the new
dict
implementation:As of python 3.6
**kwargs
order [PEP468] and class attribute order [PEP520] are preserved. The new compact, ordered dictionary implementation is used to implement the ordering for both of these.你所要求的是不可能的,但如果 JSON 语法中的配置文件就足够了,你可以做一些事情与
json
模块类似 :What you are asking for is impossible, but if a config file in JSON syntax is sufficient you can do something similar with the
json
module:我找到的一个解决方案是修补 python 本身,使 dict 对象记住插入的顺序。
这适用于所有类型的语法:
等等。
我从 ordereddict C 实现“noreferrer">https://pypi.python.org/pypi/ruamel.ordereddict/ 并合并回主 python 代码中。
如果您不介意重新构建 python 解释器,这里有一个 Python 2.7.8 的补丁:
https://github.com/fwyzard/cpython /compare/2.7.8...ordereddict-2.7.8.diff
。一个
The one solution I found is to patch python itself, making the
dict
object remember the order of insertion.This then works for all kind of syntaxes:
etc.
I have taken the
ordereddict
C implementation from https://pypi.python.org/pypi/ruamel.ordereddict/ and merged back into the main python code.If you do not mind re-building the python interpreter, here is a patch for Python 2.7.8:
https://github.com/fwyzard/cpython/compare/2.7.8...ordereddict-2.7.8.diff
.A
如果您正在寻找一种获得易于使用的初始化语法的方法 - 考虑创建 OrderedDict 的子类并向其添加更新字典的运算符,例如:
d will be- OrderedMap([(1, 2) , (4, 3), ('key','value')])
使用切片语法的另一个可能的语法糖示例:
If what you are looking for is a way to get easy-to-use initialization syntax - consider creating a subclass of OrderedDict and adding operators to it that update the dict, for example:
d will be- OrderedMap([(1, 2), (4, 3), ('key','value')])
Another possible syntactic-sugar example using the slicing syntax: