0

我正在 python2.6 中阅读字典,如下所示我知道 Python3.6 将按照声明的顺序读取字典,但我需要在 Python2.6 中实现这一点(OrderedDict 在 Python2.6 中也不可用)

numbermap = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

>>> for k, v in numbermap.iteritems():
...    print(k,v)
...
('four', 4)
('three', 3)
('five', 5)
('two', 2)
('one', 1)

我希望输出是

('one',1)
('two', 2)
('three', 3)
('four', 4)
('five', 5)

我需要边看字典边写。在 Python 2.6 中实现这一点的任何想法?

4

3 回答 3

0

看来您想要一个有序的字典。如果您可以使用 Python 2.7,请查看collections.OrderedDicthttps ://docs.python.org/2/library/collections.html#collections.OrderedDict

如果您必须坚持使用 2.6,这里有一些建议:https ://stackoverflow.com/a/1617087/3061818 (但您可能应该前往字典:如何保持键/值与声明的顺序相同?

于 2018-11-15T14:23:58.760 回答
0

排序字典有许多可用的实践。您可以查看以下示例。

第一个例子:

>>> import operator
>>> numbermap = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> sorted_maps = sorted(numbermap.items(), key=operator.itemgetter(1))
>>> print(sorted_maps)
[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]

第二个例子:

>>> import collections
>>> sorted_maps = collections.OrderedDict(numbermap)
>>> print(sorted_maps)
OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)])
于 2018-11-15T14:24:06.530 回答
-1

1 反转键值,

2 对作为值的新键进行排序

我的解决方案是对键进行排序

听起来像作弊,但有效:

首先调用一些东西来反转dict

for i in sort(numbermap.keys()):
  print(i,numbermap[i])
于 2018-11-15T14:26:00.153 回答