Why are there no ordered dictionaries?
Alex Martelli
aleax at mail.comcast.net
Sun Nov 20 21:09:47 EST 2005
bonono at gmail.com <bonono at gmail.com> wrote:
...
> there are at least two behaviour. What I need is a "preferred order".
> Say if I have designed a web form(correspond to a database table), I
> just want say 3 fields that goes before anything else in the
> presentation. The rest I don't care as the DBA may create more fields
> later which I don't want to then update my code yet again.
preferred_fields = ['foo', 'bar', 'baz']
def process_preferred_fields():
global preferred_fields
temp = {}
for i, field in enumerate(preferred_fields):
temp[field] = '%s%s' % (chr(0), chr(i))
preferred_fields = temp
process_preferred_fields()
del process_preferred_fields
def sort_key(akey, preferred_fields=preferred_fields):
return preferred_fields.get(akey, akey)
del preferred_fields
## ...build dictionary d...
# now output d...:
for k in sorted(d, key=sort_key):
print k, d[k]
Season to taste if you want non-preferred fields emitted other than
alphabetically, or if you want to wrap this stuff into a class, etc.
(Note: untested code, so typos &c are quite possible). This assumes
that no 'real' key is a non-string, and no 'real' key starts with
chr(0), but it's quite easy to tweak for slightly different specs (at
worst by defining a custom type designed to always compare less than any
real key, and wrapping the preferred_fields entry in instances of that
custom type... having such instances compare with each other based on
the index within preferred_fields of the key they're wrapping, etc etc).
Alex
More information about the Python-list
mailing list