dict filter

Subcommand of dict that returns a subset of a dictionary according to some filtering rule.

dict filter dictionaryValue key ?globPattern …?
dict filter dictionaryValue value ?globPattern …?
dict filter dictionaryValue script { keyVar valueVar } script

HaO: an example session with the script option:

% set d [dict filter {k1 v1 k2 v2} script {k v} {return [expr {$k eq "k1"}]}]
1

So return might not be the right command. It stops the script and nothing is assigned to d.

Lets try without it:

% set d [dict filter {k1 v1 k2 v2} script {k v} {expr {$k eq "k1"}}]
k1 v1

That worked !

Lars H: Also note the following possibility

 % dict filter {k1 v1 k2 v2 k3 v3} key k1 k3
 k1 v1 k3 v3

(When there is a list of exact entries you want to keep, then the key form may be more convenient.)


Fabricio Rocha - 21 Jul 2011 - Could anyone who know the dict internals tell about how does the search performed by dict filter works? And how it performs in comparison to searches made with dict for and other "manual", script-based search methods?

Lars H: Except for a few cases that can be optimised, dict filter works very much like the obvious script-level emulation in terms of dict for. For example, they both use the same public Tcl_DictObjFirst/Tcl_DictObjNext interface for iterating over the dictionary elements. A dict filter is however likely to be faster whenever that is precisely what you wants to do, due to less overhead for updating Tcl variables and such.