This is not necessarily the current version of this TIP.
| TIP: | 342 |
| Title: | Dict Get With Default |
| Version: | $Revision: 1.3 $ |
| Author: | Lars Hellström <Lars dot Hellstrom at residenset dot net> |
| State: | Draft |
| Type: | Project |
| Tcl-Version: | 8.7 |
| Vote: | Pending |
| Created: | Thursday, 27 November 2008 |
| Keywords: | dictionary, default value |
A new subcommand of dict is proposed, which returns a dictionary value if it exists and returns a per-call default otherwise.
The dict command will get a new subcommand
dict getwithdefault dictionary key ?key ...? value
(I consider the name of this subcommand very much open for discussion) which modulo error messages behaves like
proc dict_getwithdefault {D args} {
if {[dict exists $D {*}[lrange $args 0 end-1]]} then {
dict get $D {*}[lrange $args 0 end-1]
} else {
lindex $args end
}
}
i.e., it returns the value from the dictionary corresponding to the sequence of keys if it exists, or the default value otherwise. As with dict exists, it is OK (and will cause the default value to be returned) if one of the keys is missing from its dictionary, but an error is thrown if this path of keys cannot be traversed because the value associated with the previous key is not a dictionary.
It is clear that getting a value from a dictionary if it exists and using a default otherwise is a common operation, but it is also clear that this can be carried out with a combination of existing Tcl commands. Hence the issue is whether a new subcommand for this improves efficiency and convenience of this operation enough to justify the possible bloat it brings.
One approach that has been suggested for providing default values is to combine dict get with dict merge, like so:
dict get [dict merge {-apa bar} $D] -apa
This approach is however appropriate mainly in situations where several keys are given fixed defaults simultaneously. Compared to dict getwithdefault, it has the following disadvantages:
It cannot be used for keys in nested dictionaries.