Sorting dictionaries (code example)
Published: Wednesday, Dec 26, 2007 Last modified: Tuesday, Nov 26, 2024
Something I use: b = j.cos.items() b.sort(lambda a, b: cmp(b[1],a[1])) # sort by value. [0] would be the key b = b[:50] # get top fifty values j.cos = dict(b) Really badly highlighted with:
source-highlight -spython -fxhtml sort.py
Try use the Basic style sheet?
#!/usr/bin/env python2 """ Explicit dict (mapping type) definition, and method examples to show how to sort the partic. value in the tuple """ results = { 'tdk' : (0.0424, 0.0343), 'td' : (0.0309, 0.0317), 'tk' : (0.0449, 0.0348), 't' : (0.0301, 0.0308), 'dk' : (0.0480, 0.0352), 'd' : (0.0285, 0.0244), 'k' : (0.0488, 0.0357), } def sort(dict, item): """ This is a typical list comprehension method I use to sort a dict by it's value """ l = [(v[item], k) for k, v in dict.items()] l.sort() l.reverse() return l def show(list): """ Shows a ranked output of sorted list """ count = 1 for i in list: value, key = i print count, print ': ', print key, print ' \t', print value count += 1 if __name__ == "__main__": show(sort(results, 0)) print show(sort(results, 1))