I have a dictionary that I\'ve converted to a list so I can sort by the first item. The key in the dictionary is a string (of numbers), the value is an integer which is mai
That's because they're strings.
key=lambda x: int(x[0])
Changing the key to convert the string to an int will help you, also here are some other sorting tips.
from operator import itemgetter
list_to_sort=[('89372', 2), ('89373', 1), ('89374', 1), ('89375', 1), ('89376', 1), ('89377', 1), ('228055', 1), ('228054', 1), ('228057', 2), ('228056', 1), ('228051', 1), ('228050', 1),('228053', 1), ('203184', 6), ('228059', 1), ('228058', 1), ('89370', 2), ('89371', 3), ('89372', 2), ('89373', 1), ('89374', 1), ('89375', 1), ('89376', 1), ('89377', 1)]
print list_to_sort
list_to_sort.sort()
print list_to_sort # badly sorted as described
list_to_sort.sort(key=itemgetter(0))
print list_to_sort # badly sorted as described (same as above)
list_to_sort.sort(key=lambda x: int(x[0]))
print list_to_sort # sorted well
list_to_sort.sort(key=lambda x: int(x[0]), reverse=True)
print list_to_sort # sorted well in reverse
Side note on building the list to sort from the dict. iteritems() is a nicer way of doing what you do with the following
dict_List = [(x, FID_GC_dict[x]) for x in FID_GC_dict.keys()]
dict_List = [(k,v) for k,v in FID_GC_dict.iteritems()]