我有一个简单的字典,如下所示:
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
注意:以前从未有过这种情况,但是由于某种原因,它才刚刚开始发生,我确实需要按正确的顺序排列这些键。
也请注意::由于实际数据具有不应该进行排序的字符串键,因此仅对其进行排序是不可行的。
答案 0 :(得分:4)
对于python 3.6,维护插入顺序的字典是一个实现细节。在python 3.7中,它得到保证和记录。您没有指定要使用哪个版本的Python,但我认为它早于3.6。一种选择是使用有序字典,即来自collections模块的OrderedDict,其中保证了旧版本python的插入顺序。
答案 1 :(得分: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)