我正在尝试更改字典中“键”的顺序,但没有成功。 这是我最初的字典:
Not_Ordered={
'item':'book',
'pages':200,
'weight':1.0,
'price':25,
'city':'London'
}
我是否有机会根据键顺序列表更改顺序,如下所示:
key_order=['city', 'pages', 'item', 'weight', 'price']
注意:
- 我使用的是 Python 3.5.2。
- 我不是要对键进行排序。
- 我知道 Python 3.6 遵循插入。
- 此外,我知道 OrderedDict,但它给了我一个列表,但我 查找字典作为最终结果。
最佳答案
从 3.7 开始,字典“正式”按插入顺序维护。他们在 3.6 中是这样排序的,但在 3.7 之前没有保证。在 3.6 之前,您无法执行任何操作来影响键出现的顺序。
但是可以使用 OrderedDict
代替。我不明白你的“但它给了我一个 list ”的反对意见 - 我看不出这在任何意义上都是真的。
你的例子:
>>> from collections import OrderedDict
>>> d = OrderedDict([('item', 'book'), ('pages', 200),
... ('weight', 1.0), ('price', 25),
... ('city', 'London')])
>>> d # keeps the insertion order
OrderedDict([('item', 'book'), ('pages', 200), ('weight', 1.0), ('price', 25), ('city', 'London')])
>>> key_order= ['city', 'pages', 'item', 'weight', 'price'] # the order you want
>>> for k in key_order: # a loop to force the order you want
... d.move_to_end(k)
>>> d # which works fine
OrderedDict([('city', 'London'), ('pages', 200), ('item', 'book'), ('weight', 1.0), ('price', 25)])
不要被输出格式搞糊涂了! d
被显示 为对列表,传递给 OrderedDict
构造函数,为清楚起见。 d
本身不是列表。
关于python - 如何使用另一个列表作为键的引用来更改 Python 3.5 字典中键的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52139110/