Version 15 of dict tips and tricks

Updated 2008-06-20 07:12:58 by jmn

dicts are just like name value pair lists (but you shouldn't rely on any particular order of the pairs!) RS 2008-06-09: In fact, this is no longer true - from 8.5.0, dicts have a "chronological" order - each added element appears at the end. So you can even apply custom sorting of dict keys for display purposes:

 proc dict'sort {dict args} {
    set res {}
    foreach key [lsort {*}$args [dict keys $dict]] {
        dict set res $key [dict get $dict $key] 
    }
    set res
 }

#-- Test:

 set d1 {foo 1 bar 2 grill 3}
 puts 1:[dict'sort $d1]             ;# 1:bar 2 foo 1 grill 3
 puts 2:[dict'sort $d1 -decreasing] ;# 2:grill 3 foo 1 bar 2

Just like the results of [array get], so you can [array set X [dict filter]]] or (conversely) [dict get [array get X] key].

So, you can define a proc fred {args} and then immediately treat $args as a dict, if (and only if) the values passed have the form of a dict - no special processing is required (rather, the shimmering occurs in the background.

This is useful for passing named arguments to a proc, sort of like the various options packages: [dict get $args -option] will fetch any value passed as -option value.

[dict with] alters the enclosing scope

So if you have a dict X, [dict with X {}] will construct and initialize variables with the same names and values as X's contents.

This is useful for passing around collections of named values.

You could use it to populate the variables in a namespace (for, say, a collection of defaults) [namespace eval dict with $dv {}]


JMN 2008-06-20 It appears that you can extend a dict using lappend. For the case of a loop where you know the newly added keys are not currently in the dict - might this be faster than using dict set? e.g

 foreach val $newValues {
  lappend mydict [uuid::uuid generate] $val
 }

or

 lappend mydict {*}$newPairs

It also seems that even if you do lappend a key that is already in the dict, the [dict get], [dict size] etc methods still do the sensible thing, and use the latest entry in the list for a particular key. After this, upon using [dict set] - the earlier duplicate key-value pairs are automatically removed anyway.

I guess there might be some sort of shimmering in using list methods on the dict, but presumably in the above case the lappend would still be a win for large datasets because the existence of the key doesn't need to be checked each time a new value is added. Perhaps this gain is lost anyway once the dict is converted back to a proper dict value.

I've not had a chance to test the relative performance of this yet... so don't consider it as a tip/trick til you've verified it helps for your particular case!

In particular - it might be worth comparing the above with:

 set mydict [dict merge $mydict $newPairs]