[Tutor] Why is an OrderedDict not sliceable?

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Jan 25 07:22:05 EST 2016


On 24 January 2016 at 19:47, Albert-Jan Roskam <sjeik_appie at hotmail.com> wrote:
>>
>> You appear to be confusing ordered and sorted.

>   You are correct. Is there a difference in the way those terms are used colloquially vs. in the field of Computer Science (Note: English is not my mother tongue)? Anyway, this page seems to suggest that "Ordered" means "gets messed up upon insertion, deletion, update: http://stackoverflow.com/questions/1084146/what-is-the-difference-between-an-ordered-and-a-sorted-collection

An ordered collection will preserve its order if not mutated. If
mutated the operation will have a well defined effect on the order.
For example list.append(a) adds a new element and the new element will
always be at the end of the list regardless of its value. A list might
be in sorted order (i.e. after you have called the .sort() method) but
when you call append the new element will go at the end so that it is
no longer sorted.

A sorted collection has a sort key and ensures that it always has an
order that corresponds to sorting by that key. So when you add a new
element the container will somehow ensure that it ends up in the right
position to keep the container sorted.

If you use an ordered container initialised with sorted data (as you
seem to be doing) then the distinction is only important if you mutate
the container. Specifically in the case of an OrderedDict which you
want sorted by keys the distinction is only important if you add new
keys to the OrderedDict. Any new keys will be implicitly added at the
end of the OrderedDict's ordering (as if you called append on a list).
Removing a key with e.g. pop() is fine and changing the value
associate with a key is fine: only adding new keys will break the sort
order.

So if you're not adding new keys to the OrderedDict as you work then
there is no reason not to use it in this situation.

--
Oscar


More information about the Tutor mailing list