klenwell information services : PythonSequences

Python Sequences

return to DevPython

Dicts, lists, sets, and other things of sequence.

Sorting

Dict by Value

ref: http://blog.client9.com/2007/11/sorting-python-dict-by-value.html
list_of_kv_tuples = sorted(your_dict.iteritems(), key=lambda (k,v): (v,k))

# reverse sort (highest to lowest)
list_of_kv_tuples = sorted(your_dict.iteritems(), key=lambda (k,v): (v,k), reverse=True)


List of Tuple by Given Index

ref: http://stackoverflow.com/questions/3121979/python-sort-list-tuple-in-list
# reverse sort (highest to lowest) by second item in each tuple
sorted_list = sorted(list_of_tuples, key=lambda tup: tup[1], reverse=True)


Sort Simple List

ref: http://docs.python.org/library/stdtypes.html#mutable-sequence-types
# sorts in place
unsorted_list.sort()
a_dict.keys().sort(reverse=True)


References

http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange