Python字典以随机形式返回键

2024-06-16 09:03:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

注意:以前从未出现过这种情况,但出于某种原因,它刚刚开始发生,我真的需要按正确顺序排列这些键。你知道吗

另请注意:简单地排序将不起作用,因为实际数据具有不应排序的字符串键。你知道吗


Tags: tbrowsprintcolsstbs0sample2sample1
2条回答

对于Python3.6,维护插入顺序的字典是一个实现细节。在python3.7中,它是有保证和文档记录的。您没有指定要使用哪个版本的Python,但我假设它早于3.6。一种选择是使用一个有序字典,来自collections模块的OrderedDict,在这里插入顺序对于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)

相关问题 更多 >