[英]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.