Skip to main content
 首页 » 编程设计

Python 按索引排序

2025年05月04日10del

假设有一本字典

foo = {'b': 1,  'c':2,  'a':3 } 

我想按照字典中项目出现的顺序遍历这个字典。

for k,v in foo.items(): 
    print k, v 

打印

a 3 
c 2 
b 1 

如果我们使用 sorted() 函数:

for k,v in sorted(foo.items()): 
    print k, v 

打印

a 3 
b 1 
c 2 

但我需要它们按照它们在字典 i;e 中出现的顺序

b 1 
c 2 
a 3 

我如何实现这一点?

请您参考如下方法:

字典没有顺序。如果你想这样做,你需要在你的原始列表中找到一些排序方法。或者,按照键的保存顺序将键保存在列表中,然后使用这些键作为键访问字典。

来自 The Python Docs

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

示例 -

>>> testList = ['a', 'c', 'b'] 
>>> testDict = {'a' : 1, 'c' : 2, 'b' : 3} 
>>> for elem in testList: 
        print elem, testDict[elem] 
 
 
a 1 
c 2 
b 3 

或者更好,使用 OrderedDict -

>>> from collections import OrderedDict 
>>> testDict = OrderedDict([('a', 1), ('c', 2), ('b', 3)]) 
>>> for key, value in testDict.items(): 
        print key, value 
 
 
a 1 
c 2 
b 3