使用Python基于值对字典进行排序

2024-05-21 20:07:54 发布

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

我有一句话:

self.currentMsg={'Decimal Label value':'','SDI value':'','Label format':''}

for i in range (self.firstRowIdx, self.lastRowIdx) :
        self.currentMsg['Decimal Label value']=self.xlManager.getCellValue(i,LABEL_COL_IDX)


self.currentMsg['SDI value']= SDIValue=self.xlManager.getCellValue(i,SDI_COL_IDX)
        self.currentMsg['Label format']=LabelFormat=self.xlManager.getCellValue(i,FORMAT_COL_IDX)
 sorted_x = sorted(self.currentMsg.items(),key=operator.itemgetter('Decimal Label value'))
        print(sorted_x) 

我想根据“十进制标签值”的递增值对dict进行排序。在

我试过了:

^{pr2}$

但我得到了这个错误

TypeError: tuple indices must be integers, not str

我试过了:

sorted_x = sorted(self.currentMsg.items(), key=itemgetter('0'))

但这句话还没有整理好。 控制台显示:

[('Decimal Label value', 324.0), ('Label format', 'BNR'), ('SDI value', 'XX')]
[('Decimal Label value', 331.0), ('Label format', 'BNR'), ('SDI value', 'XX')]

[('Decimal Label value', 312.0), ('Label format', 'BNR'), ('SDI value', 'XX')]

Tags: selfformatbnrvalueitemscollabeldecimal
1条回答
网友
1楼 · 发布于 2024-05-21 20:07:54

看起来你可能有一个的dict列表,而不是adict

因此,请尝试:

sorted_x = sorted(self.currentMsg, 
    key=operator.itemgetter('Decimal Label value')) 

仔细想想,由于您使用的是self.currentMsg.items(),并且它没有引发AttributeError,所以{}可能是一个dict。 那么self.currentMsg.items()将是键/值对的元组。这与您的第一个语句相矛盾,因为它只显示3个dict的序列。在

为了更好地回答您的问题,我们需要看看self.currentMsg到底是什么样子。在

相关问题 更多 >