按排序顺序按键遍历 Python 字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14863536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:41:27  来源:igfitidea点击:

Iterate through Python dictionary by Keys in sorted order

pythonloopssortingdictionary

提问by ben

I have a dictionary in Python that looks like this:

我有一个 Python 字典,看起来像这样:

D = {1:'a', 5:'b', 2:'a', 7:'a'}

The values of the keys are mostly irrelevant. Is there are way to iterate through the dictionary by keys in numerical order? The keys are all integers.

键的值大多是不相关的。有没有办法按数字顺序按键遍历字典?键都是整数。

Instead of saying

而不是说

for key in D:
    # some code...

Can I go through the dictionary keys in the order 1, 2, 5, 7?

我可以按顺序浏览字典键1, 2, 5, 7吗?

Additionally, I cannot use the sort/sorted functions.

此外,我无法使用排序/排序功能。

采纳答案by isedev

You can use this:

你可以使用这个:

for key in sorted(D.iterkeys()):
    .. code ..

In Python 3.x, use D.keys()(which is the same as D.iterkeys()in Python 2.x).

在 Python 3.x 中,使用D.keys()(与D.iterkeys()Python 2.x 中相同)。

回答by Rohit Jain

You can get the list of keys using dict.keys(), and then iterate over a sorted view of the list:

您可以使用 获取键列表dict.keys(),然后遍历列表的排序视图:

for key in sorted(D.keys()):
    print key, D[key]

回答by kindall

Taking into account your stipulation that you don't want to sort, and assuming the keys are all integers, you can simply find the maximum and minimum values of the keys, then iterate over that range and check whether each is actually in the dictionary.

考虑到您不想排序的规定,并假设键都是整数,您可以简单地找到键的最大值和最小值,然后遍历该范围并检查每个键是否确实在字典中。

for key in xrange(min(D), max(D) + 1):
    if key in D:
        print D[key]

This isn't very efficient, of course, but it willwork, and it avoids sorting.

这当然不是很有效,但它起作用,并且避免了排序。

回答by JCash

Assuming that the keys/values are inserted in order, you can use an OrderedDict:

假设键/值按顺序插入,您可以使用OrderedDict

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d[1] = 'a'
>>> d[2] = 'a'
>>> d[5] = 'b'
>>> d[7] = 'a'
>>> d
OrderedDict([(1, 'a'), (2, 'a'), (5, 'b'), (7, 'a')])
>>> d.keys()
[1, 2, 5, 7]