I have a python dictionary setup like so
mydict = { 'a1': ['g',6],
'a2': ['e',2],
'a3': ['h',3],
'a4': ['s',2],
'a5': ['j',9],
'a6': ['y',7] }
I need to write a function which returns the ordered keys in a list, depending on which column your sorting on so for example if we're sorting on mydict[key][1] (ascending)
I should receive a list back like so
['a2', 'a4', 'a3', 'a1', 'a6', 'a5']
It mostly works, apart from when you have columns of the same value for multiple keys, eg. 'a2': ['e',2] and 'a4': ['s',2]. In this instance it returns the list like so
['a4', 'a4', 'a3', 'a1', 'a6', 'a5']
Here's the function I've defined
def itlist(table_dict,column_nb,order="A"):
try:
keys = table_dict.keys()
values = [i[column_nb-1] for i in table_dict.values()]
combo = zip(values,keys)
valkeys = dict(combo)
sortedCols = sorted(values) if order=="A" else sorted(values,reverse=True)
sortedKeys = [valkeys[i] for i in sortedCols]
except (KeyError, IndexError), e:
pass
return sortedKeys
And if I want to sort on the numbers column for example it is called like so
sortedkeysasc = itmethods.itlist(table,2)
So any suggestions?
Paul