-1

I have a dict:

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) 

I would like to sort the dict based on increasing value of 'Decimal Label value'.

I've tried this:

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

but I get this error

TypeError: tuple indices must be integers, not str

then I've tried this:

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

but the dict is still not sorted. the console shows:

[('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')]
  • See related: http://stackoverflow.com/questions/289/how-do-you-sort-a-dictionary-by-value?rq=1 – EdChum Mar 09 '15 at 13:49

1 Answers1

1

It looks like you might have a list of dicts, not a dict.

Therefore, try:

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

On second thought, since you are using self.currentMsg.items() and it did not raise an AttributeError, it appears self.currentMsg is probably a dict. Then self.currentMsg.items() would be a tuple of key/value pairs. This contradicts your first statement, since it only shows a sequence of 3 dicts.

To better answer your question, we need to see what self.currentMsg really looks like.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677