A dict
inherently has an arbitrary order.
If you just want to access it in a specific order one time, you can just sort it. If you don't know how to sort things using anything other than the default ordering, read the Sorting HOW TO. But basically:
for k, v in sorted(d.items(), key=lambda kv: kv[1].ID):
print('{}: {}'.format(k, v))
If you actually want to store them in that order, you need some time that maintains order. Of course a list
will work, but an OrderedDict
works like a dict
, except that it maintains the order of insertion, which is more convenient for most use cases. So, if you create a new OrderedDict
and then insert everything into it in sorted order, that would probably solve your problem:
d1 = { your original dict }
d2 = collections.OrderedDict()
for key in sorted(d1, key=lambda k: d1[k].ID):
d2[key] = d1[key]
You can simplify this down to one line if you understand comprehensions:
d2 = OrderedDict(sorted(d1.items(), key=lambda kv: kv[1].ID))
Variations on similar examples are shown in the docs under OrderedDict
Examples and Recipes.
If you instead want the dictionary to maintain sorted order, you will need some kind of sorted dict class. The stdlib doesn't come with such a class, but there are many options available on ActiveState and PyPI. Some are implemented as an OrderedDict
that re-sorts itself every time you update them (or, sometimes, the first time you access them after an update, which allows a long chain of updates to avoid a long chain of sorts). Others use bisect
or a search tree (e.g., a binary red-black tree or a 10-ary B-tree) to insert elements in the right place.