Python字典以随机顺序返回键

3

我有一个简单的字典,格式如下:

stb = {
    'TH0':{0:'S0',1:'Sample1',2:'Sample2',3:'Sample4'},
    'TH1':{0:'Sa0',1:'Sample1',2:'Sample2',3:'Sample4'},
    'TH2':{0:'Sam0',1:'Sampled1.0',2:'Sampled2.0',3:'Sampled4.0'},
    'TH3':{0:'Samp0',1:'Sample1',2:'Sample2',3:'Sample4'},
    'TH4':{0:'Sampl0',1:'Sample1',2:'Sample2',3:'Sample4'},
}
tb = stb

theaders = []
for k in tb.keys():
    theaders.append(k)
columns = len(theaders)
rows = len(tb[theaders[0]])
print(tb[theaders[0]])
print('Cols: ',columns)
print('Rows: ',rows)

for h in theaders:
    print(h)
`

问题在于,每次运行这段代码时,theaders的值都是随机排序的。例如,第一次运行:

{0: 'Samp0', 1: 'Sample1', 2: 'Sample2', 3: 'Sample4'}
Cols:  5
Rows:  4
TH3
TH0
TH4
TH1
TH2

第二次运行:

{0: 'S0', 1: 'Sample1', 2: 'Sample2', 3: 'Sample4'}
Cols:  5
Rows:  4
TH0
TH2
TH4
TH1
TH3

注意:以前从未出现这种情况,但由于某些原因,现在它开始发生了,我真的需要这些键按照正确的顺序。

另外请注意:简单地排序是不起作用的,因为真实数据具有不应被排序的字符串键。


1
字典在3.7版本之后保留插入顺序,而在此之前需要使用OrderedDict - ic3b3rg
2个回答

4

对于Python 3.6来说,保持插入顺序的字典是一种实现细节。而在Python 3.7中,这已经被保证并且有文档支持。由于你没有指定你使用的Python版本,但我假设它比3.6早,因此一个选择是使用有序字典(OrderedDict)来保证插入顺序,该模块位于collections中。


1
可能是这个版本有问题,我使用的是3.5,因为它随Ubuntu Xenial一起安装。但是以前为什么它还能正常工作呢?是我只是运气好吗? - silverhash
你之前只是运气好或者没有注意到 =) - Kevin S
我猜,好吧...让我试试看。 - silverhash

3

这是因为在Python中,字典是无序的。如果您希望保留键的顺序,可以尝试使用 OrderedDict,如下所示。

from collections import OrderedDict

stb = OrderedDict(
    TH0 = {0:'S0',1:'Sample1',2:'Sample2',3:'Sample4'},
    TH1 = {0:'Sa0',1:'Sample1',2:'Sample2',3:'Sample4'},
    TH2 = {0:'Sam0',1:'Sampled1.0',2:'Sampled2.0',3:'Sampled4.0'},
    TH3 = {0:'Samp0',1:'Sample1',2:'Sample2',3:'Sample4'},
    TH4 = {0:'Sampl0',1:'Sample1',2:'Sample2',3:'Sample4'},
)

tb = stb # As I see, this is not necessary (as we are not using std anywhere in the 
         # following code)

theaders = []
for k in tb.keys():
    theaders.append(k)

columns = len(theaders)
rows = len(tb[theaders[0]])

print(tb[theaders[0]])
print('Cols: ',columns)
print('Rows: ',rows)

for h in theaders:
    print(h)

在实际代码中,这是一个实用类,因此stb在初始化时被解析并进行了一些清理,所以是必要的,但在这个例子中可能不是必要的。无论如何,谢谢。 - silverhash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接