sorteddict PEP proposal [started off as orderedict]

James Stroud jstroud at mbi.ucla.edu
Tue Sep 25 22:28:25 CEST 2007


Mark Summerfield wrote:
> On 2007-09-25, Andrew Durdin wrote:
>> e.g. sorteddict({1:'a', 3:'b': 5:'c', 99:'d'})[3]  should return 'b', not
>> 'd'.
> 
> The sorteddict really does work in key order, so:
> 
>     d = sorteddict({1:'a', 3:'b', 5:'c', 99:'d'})
>     d.items()
>     [(1, 'a'), (3, 'b'), (5, 'c'), (99, 'd')]
> 
> If you do d[3] you will get 'd' since that is the 4th sequential item.
> If you want to get the item with _key_ 3 then use value():
> 
>     d.value(3)
>     'd'

If a quorum opinion might sway you, I have found, after prolonged and 
almost metaphysical type meditation on and experimentation with the 
subject, that it would be undesirable to support the type of ambiguous 
item access that you suggest.

1.  It would break symmetry with __setitem__:

     >>> d = sorteddict({1:'a', 3:'b', 5:'c', 99:'d'})
     >>> d[2] = 'x'
     >>> d[2]
     'b'

     The need for a work-around in this case (i.e. value()) sends
     a flag that something is clumsy about the interface. It seems that
     the presence of the value() method exists simply to compensate
     for the "broken" design. More symmetrical would be to make value()
     or some other well named method return a value at an index.

2.  Such ambiguity breaks 100% compatiblity with the built-in
     dict. I think the success of a sorted dict would be tied quite
     closely to its being a superset of dict. This compatibility
     not only makes it easy for people to start using sorteddict
     without remembering the distinctions but should also reduce
     the need for explicit type checking in libraries that use
     sorteddict.


James



More information about the Python-list mailing list