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
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