Dictionaries in Python are not meant to be sorted, so for example giving a sorted output will always involve making at least a temporary list version of it, like:
Would that be good enough? If not...
Do you access the dictionary by key anywhere in your code? If not, you could instead make a list of tuples and sort that, like:
d1 = [(2, 9), (5, 4), (9,1)]
If you want to sort this by the second value of a tuple, you'd need a tiny lambda though. ;)
d1. sort(key=lambda element: element)
If you insist on avoiding lambda, you can just put the 'value' first in the tuple, because the default for sorting sequences is the first element (if equal: next, and so on).
To quickly get your dictionary into this format you could write:
d1 = sorted([x[::-1] for x in d1.items()])
d1 = sorted([(b, a) for (a, b) in d1.items()])
KrOW, interesting, I haven't used these yet!
I have a question:
These dicts seem to sort by order of entry, right? So if you want your dictionary sorted, you'd have to pre-sort it anyway, like it's demonstrated in the doc, using 'sorted(...)' .
And since every new entry will be entered at the end of the OrderedDict, will that not force you to re-sort the thing via 'sorted' every time you change it?
@HonFu Yes. Yes. And yes :).
Every time that you add some key, this is appended to last position then if you want apply sort, you have to rebuild the ordered dict (its better use it only for fixed items)