[英]Python dictionary returns keys in random order
我有一个简单的dicts字典如下:
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
以随机顺序显示值。例如,First Run:
{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,维护插入顺序的字典是一个实现细节。 在python 3.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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.