Why are there no ordered dictionaries?
Christoph Zwerschke
cito at online.de
Wed Nov 23 17:00:29 EST 2005
Fuzzyman wrote:
> So what do you want returned when you ask for d1[1] ? The member keyed
> by 1, or the item in position 1 ?
In case of conflict, the ordered dictionary should behave like a
dictionary, not like a list. So d1[1] should be the member keyed by 1,
not the item in position 1. Only in case there is no member keyed by 1,
the item in position 1 could be returned, but I think that would be too
adventurous a hattrick and can lead to big confusion. Better to raise a
KeyError in that case.
>> But no other way to directly manipulate the keys should be provided.
> Why - don't trust yourself with it ?
No, because I think it is not needed if list operations like insert are
directly possible on your dictionary.
But maybe methods such as setkeys() and setvalues() would be nice to
have in addition.
Instead of writing d.sequence = new_sequence, I would write
d.setkeys(new_sequence). But I'm not sure what to do if new_sequence is
not a permutation of the old one. Raise a KeyError? Or even swallow
this? For instance
d = OrderedDict((1,11), (2,12))
d.setkeys((2, 1)) ==> d = OrderedDict((2, 11), (1, 12))
d.setkeys((3, 4)) ==> d = OrderedDict((3, 11), (4, 12)) (or KeyError?)
d.setvalues((12, 11)) ==> d = OrderedDict((1, 12), (2, 11))
d.setvalues((13, 14)) ==> d = OrderedDict((1, 13), (2, 14)) (always ok)
(Or maybe better set_keys in analogy to has_key?)
I hesitate making keys and values managed properties, because this would
conflict with them being methods in ordinary dicts. Ordered dicts should
resemble ordinary dicts as closely as possible. And giving it a
different name like "sequence" I find confusing and unintuitive.
A resort could be the following: If keys() is given a sequence as
argument, then use this as the new sequence of keys, and similar with
values(). This way, no new methods need to be introduced.
-- Christoph
More information about the Python-list
mailing list