Python 2.5 dictionary 2 key sort

后端 未结 6 1750
灰色年华
灰色年华 2021-01-01 19:47

I have a dictionary of 200,000 items (the keys are strings and the values are integers).

What is the best/most pythonic way to print the items sorted by descending v

6条回答
  •  無奈伤痛
    2021-01-01 20:18

    Building on Thomas Wouters and Ricardo Reyes solutions:

    def combine(*cmps):
        """Sequence comparisons."""
        def comparator(a, b):
            for cmp in cmps:
                result = cmp(a, b):
                if result:
                    return result
            return 0
        return comparator
    
    def reverse(cmp):
        """Invert a comparison."""
        def comparator(a, b):
            return cmp(b, a)
        return comparator
    
    def compare_nth(cmp, n):
        """Compare the n'th item from two sequences."""
        def comparator(a, b):
            return cmp(a[n], b[n])
        return comparator
    
    rev_val_key_cmp = combine(
            # compare values, decreasing
            reverse(compare_nth(1, cmp)),
    
            # compare keys, increasing
            compare_nth(0, cmp)
        )
    
    data = { 'keyC':1, 'keyB':2, 'keyA':1 }
    
    for key, value in sorted(data.items(), cmp=rev_val_key_cmp):
        print key, value
    

提交回复
热议问题