1. Jason Scheirer
  2. sorteddict

Wiki

Clone wiki

sorteddict / Home

Hi

This is the page for my SortedDict project. It's like a Python dictionary, but it keeps key/value pairs stored in key-sorted order. You can use any object that can do comparisons (responds to cmp(x, y)) as a key.

Advantages

  • In-order traversal of keys
  • Ability to key things by unhashable values (lists, dicts, etc)
  • Acts like a dict

Disadvantages

  • Assumes you know what you're doing: if your key is mutable and you change it, it can get lost
  • Undefined behavior if any comparison fails/does not behave consistently
  • Can perform up to 15% worse than Python dicts in worst-case random read/write cases
  • Not as tested/stable as Python dicts

Getting Started

First, install it:

python setup.py install

Then, use it:

import ordereddict
import random
od = ordereddict.OrderedDict()

y = range(100) + [str(x) for x in xrange(100)]
random.shuffle(y)

for i, x in enumerate(y):
    od[x] = "Entry #%i"%i

for key in y[:25]:
    del od[key]

for item in sorted(y):
    print "od[%r] = %r" % (item, od.get(item, "NOT FOUND??"))

print ", ".join(repr(key) for key in od)
print ", ".join(repr(value) for value in od.values())
print ", ".join(repr(item) for item in od.items())

print "100 in od?", 100 in od

Updated