问题描述
我觉得Python字典不会按照插入顺序存储密钥令人讨厌。最近,我已经开始使用OrderedDict,因为它覆盖了这个缺点,比较方便使用(例如,迭代CSV文件列,列顺序应该与字典的键顺序相匹配)。
I find it annoying that Python dictionaries do not store keys in insertion order. Recently, I've started using OrderedDict, which is more convenient to use since it covers this drawback (for example, iterating over columns of a CSV file where the column order is supposed to match the key order of a dictionary).
那就是说,字典有一个OrderedDict有什么明显的优势吗?如果是这样,他们是什么?
That said, are there any distinct advantages that a dictionary has over an OrderedDict? If so, what are they?
推荐答案
字典是一个更简单的数据结构,占用的空间更小,更快一些。它只需要维护一个哈希表,而 OrderedDict
维护一个哈希表和一个链表。
A dictionary is a simpler data structure that takes up less space and is a bit faster. It only needs to maintain a hash table, while an OrderedDict
maintains both a hash table and a linked list.
如果您不关心键的顺序,请使用更简单的选项。
If you don't care about the order of keys, go with the simpler option.
同样不容忽视的是,语言级别支持dicts。很容易键入 {k1:v1,k2:v2}
。这是另一个胜利的dicts。一个不公平的一个,也许,但你去。
Also not to be overlooked, there's language level support for dicts. It's easy to type {k1: v1, k2: v2}
. That's another win for dicts. An unfair one, perhaps, but there you go.
这篇关于Dict over OrderedDict的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!