On Thursday, July 19, 2012 3:07:16 PM UTC-3, Georgios Petasis wrote:
> Hi all,
>
> I was looking the dict manual, and I realised that it is very easy to
> create nested directories (with dict set), but is not so easy to lappend
> values to nested dictionaries.
>
> For example:
>
> dict set d person name phone_numbers 1
>
> returns a dict with nested dictionaries:
>
> person {name {phone_numbers 1}}
>
> But what is the most efficient way to append a new phone number to the
> last dict?
>
> Initially I thought that the following would work:
>
> dict lappend d person name phone_numbers 2
>
> But it does not. What is the best alternative?
>
> (From the manual I am not sure that I understood what dict update & dict
> with are supposed to do. I am totally lost with the examples.)
Since [dict] is an ensemble command, you can easily add your own
subcommand to [lappend] to nested dictionaries.
The following version uses [dict with]:
proc ::tcl::dict::lappend2 {dict args} {
upvar 1 $dict d
with d {*}[lrange $args 0 end-2] {
::lappend [lindex $args end-1] [lindex $args end]
}
}
namespace ensemble configure dict -map \
[dict merge [namespace ensemble configure dict -map] \
{lappend2 ::tcl::dict::lappend2}]
testing:
% dict set d person name phone_numbers 1
person {name {phone_numbers 1}}
% dict lappend2 d person name phone_numbers 2
1 2
% set d
person {name {phone_numbers {1 2}}}
Regards
Emiliano