Python字典以随机顺序返回键

Python字典以随机顺序返回键,python,python-3.x,Python,Python 3.x,我有一个简单的口述,如下所示: 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

我有一个简单的口述,如下所示:

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
注意:以前从未出现过这种情况,但出于某种原因,它刚刚开始出现,我真的需要按正确的顺序排列这些钥匙


另请注意:简单地对其进行排序是行不通的,因为实际数据的字符串键不应进行排序。

对于python 3.6,维护插入顺序的字典是一个实现细节。在Python3.7中,它是有保证和文档记录的。您没有指定使用哪个版本的Python,但我假设它早于3.6。一种选择是使用有序字典,OrderedDictionary from the collections模块,在该模块中,插入顺序对于较早版本的python是有保证的

这是因为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)

dicts从3.7开始保留插入顺序,在此之前需要
OrderedDict
。可能就是这样,我使用的是3.5,因为它是Ubuntu Xenial附带的。但是它以前是怎么工作得很好的呢,还是我只是运气好呢?你之前只是运气好,或者没有注意到=)我猜,好吧..让我试试看,在真正的代码中,这是一个实用类,所以
stb
在初始化时被解析,并且做了一些清理,所以是的..这是必要的,但在本例中可能不需要..谢谢