set alpha {a 1 b 2 c 3}
dict get $alpha b
# => 2
dict get $alpha d
# (ERROR) key "d" not known in dictionary
If dict get
is used to retrieve the value of a missing key, an error is raised. To prevent the error, use dict exists
:
if {[dict exists $alpha $key]} {
set result [dict get $alpha $key]
} else {
# code to deal with missing key
}
How to deal with a missing key of course depends on the situation: one simple way is to set the result
to a default "empty" value.
If the code never attempts to retrieve other keys that are in the dictionary, dict get
will of course not fail. But for arbitrary keys, dict get
is an operation that needs to be guarded. Preferably by testing with dict exists
, though exception catching will work too.