[Newbies] Re: how to sort by key a Dictionary object?

Randal L. Schwartz merlyn at stonehenge.com
Wed Aug 26 14:50:32 UTC 2009

>>>>> "Bert" == Bert Freudenberg <bert at freudenbergs.de> writes:

Bert> On 26.08.2009, at 12:58, Overcomer Man wrote:

>> I know this was already covered but to simplify the explination for  the
>> beginner:
>> Sort is automatic for Dictionaries.

Bert> This is over-simplifying. *Printing* of dictionaries sorts  automatically. But
Bert> not regular iteration.

And this is because #printOn: contains sorting code:

    "Collection >> #printOn:"
    printOn: aStream
      "Append a sequence of characters that identify the receiver to aStream."

      self printNameOn: aStream.
      self printElementsOn: aStream

which further calls:

    "Dictionary >> #printElementsOn:"
    printElementsOn: aStream 
      aStream nextPut: $(.
      self size > 100
      ifTrue: [aStream nextPutAll: 'size '.
        self size printOn: aStream]
      ifFalse: [self keysSortedSafely
        do: [:key | aStream print: key;
          nextPutAll: '->';             
          print: (self at: key);
      aStream nextPut: $)

Note the "self keysSortedSafely".  This is another strategy for
walking a dictionary in key order.

As we were discussing this issue last night at the Portland Smalltalk meeting
after-meeting dinner, whether it is faster to grab the associations to sort
them, or to grab the keys to sort them first then go look up the values,
depends on the storage of a Dictionary.  And I suspect that since the Squeak
implementation of Dictionary already has the associations and just needs to
spit them out, that's probably going to be faster than going back to look
them up one by one, as the above code does.

Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.vox.com/ for Smalltalk and Seaside discussion

More information about the Beginners mailing list