ipetrik
ipetrik

Reputation: 2054

How to pass variable as key path to dict get in tcl?

I have the following 'multi-dimensional' dictionary

dict set atm_prms bb N [dict create volume 13.3 radius 1.65 vdw_nrg -1.0906 ]
dict set atm_prms bb CA [dict create volume 9.4 radius 1.8 vdw_nrg -0.7708 ]
dict set atm_prms bb C [dict create volume 9.82 radius 1.4 vdw_nrg -0.8052 ]
dict set atm_prms bb O [dict create volume 8.2 radius 1.4 vdw_nrg -0.6724 ]
dict set atm_prms bb OXT [dict create volume 8.2 radius 1.4 vdw_nrg -0.6724 ]
dict set atm_prms ALA CB [dict create volume 16.15 radius 1.9 vdw_nrg -1.3243 ]
dict set atm_prms ARG CB [dict create volume 12.77 radius 1.9 vdw_nrg -1.0471 ]
dict set atm_prms ARG CG [dict create volume 12.77 radius 1.9 vdw_nrg -1.0471 ]
dict set atm_prms ARG CD [dict create volume 12.77 radius 1.9 vdw_nrg -1.0471 ]
dict set atm_prms ARG NE [dict create volume 9 radius 1.65 vdw_nrg -0.738 ]
dict set atm_prms ARG CZ [dict create volume 6.95 radius 1.4 vdw_nrg -0.5699 ]
dict set atm_prms ARG NH1 [dict create volume 9 radius 1.65 vdw_nrg -0.738 ]
dict set atm_prms ARG NH2 [dict create volume 9 radius 1.65 vdw_nrg -0.738 ]
dict set atm_prms ASN CB [dict create volume 12.77 radius 1.9 vdw_nrg -1.0471 ]
dict set atm_prms ASN CG [dict create volume 9.82 radius 1.9 vdw_nrg -0.8052 ]
dict set atm_prms ASN OD1 [dict create volume 8.17 radius 1.4 vdw_nrg -0.6699 ]
dict set atm_prms ASN ND2 [dict create volume 13.25 radius 1.65 vdw_nrg -1.0865 ]

How can I use a key path stored in a variable to retrieve a value?

For instance, this works:

> puts [dict get $atm_prms ALA CB volume]
16.15

But this fails:

> set my_path {ALA CB volume}
> puts [dict get $atm_prms $my_path]
key "ALA CB volume" not known in dictionary

How do I properly use a key path that is stored in a variable?

Upvotes: 1

Views: 538

Answers (1)

glenn jackman
glenn jackman

Reputation: 247022

Because "ALA CB volume" is being substituted into the dict get command as a single word. You need to tell Tcl that you want that list expanded into separate words:

% puts [dict get $atm_prms $my_path]
key "ALA CB volume" not known in dictionary
% puts [dict get $atm_prms {*}$my_path]
16.15

See rule #5 in http://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm

Upvotes: 3

Related Questions