I have a (fixed) set of keys for which I store a value. I often look up the value for a key and increment or decrement it. A typical dict usage.
x = {'a': 1, 'b': 4, 'c': 3}
x['a'] += 1
Additionally however, just as often as incrementing or decrementing values, I also need to know the key for the i-th largest (or smallest) value. Of course I can do the sorting:
s = sorted(x, key=lambda k:(x[k],k))
s[1] == 'c'
The problem is sorting every time seems rather expensive. Especially because I only increment one item in between sorts. I feel that I could use another data structure better suited for this. A tree perhaps?