dict get

Difference between version 6 and 7 - Previous - Next
Subcommand of [dict], used for getting a value out of a dictionary or nested set of dictionaries.

    :   '''dict get''' ''dict'' ?''key …''?

----
[AMG]: Here's a [[dict getnull]] command which returns empty string rather than raise an [error] when the requested element doesn't exist.  This example uses [{*}] and [[[namespace ensemble]]].  It also takes advantage of the fact that the return value of [[[if]]] or a [proc] is the return value of the last command it executed, or empty string if it didn't execute anything.

======
proc ::tcl::dict::getnull {dictionary args} {
    if {[exists $dictionary {*}$args]} {
        get $dictionary {*}$args
    }
}
namespace ensemble configure dict -map\
    [dict replace [namespace ensemble configure dict -map]\
                  getnull ::tcl::dict::getnull]
======

Examples:

======
dict getnull {a b c {d e f g}} a    ;# b
dict getnull {a b c {d e f g}} c    ;# d e f g
dict getnull {a b c {d e f g}} c d  ;# e
dict getnull {a b c {d e f g}} c f  ;# g
dict getnull {a b c {d e f g}} h    ;# (empty string)
dict getnull {a b c {d e f g}} c h  ;# (empty string)
======
[ufko] Example kv:

======
proc kv {lst key} {
    set idx [lsearch $lst $key]    if {$idx == -1} {
        return -1
    }
    incr idx 
    return [lindex $lst $idx]
}

set L {id 100 name john}
puts [kv $L id]
set L {id 100 person {firstname Dave lastname Doe}}
puts [kv [kv $L person] lastname]
======
-----

See Also: [dict get?]

<<categories>> Command