[英]Ordered Dict, preserve initial Order
Ordered Dict: 有序字典:
import collections
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
collections.OrderedDict(sorted(d.items(), key=lambda t: t[0]))
The above example shows how to order a dict, which is unsupported by nature. 上面的示例显示了如何订购自然不受支持的字典。 However, how can i preserve the initial order rather then sorting by key or value?
但是,如何保留初始顺序,而不是按键或值排序?
Initial order is preserved for an OrderedDict
, so just put it straight in and bypass the regular dictionary: 最初的顺序被保存为
OrderedDict
,所以只是把它直并绕过正常的字典:
>>> from collections import OrderedDict
>>> od = OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
>>> od
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
Once you initialized regular dict with your items the order is gone. 用商品初始化常规字典后,订单就消失了。 So just initialize ordered dict in initial order:
因此,只需按初始顺序初始化有序字典即可:
import collections as co
co.OrderedDict([(a, b) for a, b in list_of_pairs])
# or
d = co.OrderedDict()
for a, b in list_of_pairs:
d[a] = b
Already regular dict
has no order when you defining. 在定义时,常规
dict
已经没有命令。 sort
on dict
is actually not sorting dict.It is sorting the list
containing tuples
of (key, value)
pairs. 对
dict
sort
实际上不是对dict
排序,而是对包含(key, value)
对的tuples
的list
排序。
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
s = sorted(d.items(), key=lambda t: t[0])
>>>s
[('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]
This is sorted
list of tuples
. 这是
tuples
sorted
列表。 key = lambda t: t[0]
is returning 2nd
element of tuple.So sorting based on 2nd
element of tuple
key = lambda t: t[0]
返回tuple
2nd
元素。因此,基于tuple
2nd
元素进行排序
new_d = dict(s)
>>>new_d.items()
[('orange', 2), ('pear', 1), ('apple', 4), ('banana', 3)]
That is order disappears.Inoder to maintain order, OrderedDict
is used. 那就是订单消失。为了维护订单,使用了
OrderedDict
。
For example 例如
>>>OrderedDict({"a":5})
OrderedDict([('a', 5)])
This is also maintaining list of tuples
. 这也在维护
list of tuples
。
So you have to pass
a sorted list of tuple
所以你必须
pass
一个排序list of tuple
>>>OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.