Main Content

Sorting dicts and arrays in Tcl

Archive - Originally posted on "The Horse's Mouth" - 2012-03-04 13:20:05 - Graham Ellis

In Tcl, both arrays and dicts can contain key / value pairs, where the keys are any unique string. What are the differences?

arrays are NOT simply formatted strings - they're a special structure which uses hashing techniques for managing the members, making it very fast for Tcl to access members by key, but meaning (on the down side) that you can only pass the whole array into a proc using upvar, and that you cannot sort an array. So they're similar to dicts in Python, and to hashes in Perl.

dicts are formatted strings - so you can pass them directly into procs, and you can reorder them - but they're much less efficient that arrays once you start passing around and manipulating structures of significant size. Tcl's dicts are similar in many ways to associative arrays in PHP.

If you want to output the contents of a dict, sorted, then much the easiest way up to and including release 8.5 of Tcl is to use lsort to sort a list of keys, then iterate through that list in sorted order. There's an example [here] on our web site. Should you wish to hold onto your sorted dict, then the best way to do it is to sort the keys and rebuild a new dictionary - I've also included that at the end of the example

Once version 8.6 ofTcl gets to a production release (and you have it on all your systems), you'll be able to use the -stride and index options on lsort, which will directly return you a sorted dict if you pass in a parameter 2 to the stride. Thus:
  lsort -stride 2 {grapefruit 10 banana 110 cherry 25}
will return
  banana 110 cherry 25 grapefruit 10
and
  lsort -stride 2 -index 1 -integer {grapefruit 10 banana 110 cherry 25}
wlll return
  grapefruit 10 cherry 25 banana 110