Skip to main content
 首页 » 编程设计

python之for循环的字典输出

2025年05月04日12hnrainll

我刚开始学习 codecademy 的 Python 类(class)。我正在尝试按字典中的顺序返回 dic 值。

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} 
 
 
res = residents.values() 
count = 0 
for element in res: 
    print res[count] 
    count += 1 

我收到的输出: 105 104 106

由此我了解到我并不完全理解 for 循环或字典的工作原理,我期望得到 104 105 106 作为输出。谁能解释一下?

请您参考如下方法:

字典在 Python 中没有排序。很多次我尝试在它们上面运行循环并期望输出的顺序与我给它输入的顺序相同,但它没有用。所以我想,这不是 for 循环 的错。

正如 Maroun 在评论中建议的那样,您应该为此使用 OrderedDict。