读取(声明)时打印dict迭代元素

2024-10-03 17:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读一本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)

我需要边读字典边写。在Python2.6中实现这一点有什么想法吗


Tags: in声明for字典顺序oneordereddictthree
3条回答

看来你想要一本有序的词典。如果可以使用Python2.7,请查找collections.OrderedDicthttps://docs.python.org/2/library/collections.html#collections.OrderedDict

如果您必须坚持使用2.6,这里有一些建议:https://stackoverflow.com/a/1617087/3061818(但您可能应该转到Dictionaries: How to keep keys/values in same order as declared?

1反转键值

2对新键排序,该键是值

我的解决办法是把钥匙分类

听起来像是作弊,但很管用:

先打电话叫人倒口述

for i in sort(numbermap.keys()):
  print(i,numbermap[i])

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

第一个例子:

>>> 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)])

相关问题 更多 >