2014-02-26 17 views
1

我正在尋找一種方式將一個字符串追加到內部字典中的現有成員(TCL8.5)整齊地修改內部字典中的一員

  • 使用dict append沒有好 - 只有1能使遞歸水平。
  • 我想出了dict setdict get的組合,但它非常難看。
  • 最後,我認爲dict with會有所幫助,但如果其中一個鍵與字典的名稱相同,則它可能是災難性的。

dict set cfg animals mammal cat1 meyaO1 
dict set cfg animals mammal cat2 meyaO2 
dict set cfg animals mammal cfg bar 
# Method 1 (Ugly) 
dict set cfg animals mammal cat1 "[dict get $cfg animals mammal cat1]hihi" 
puts [dict get $cfg animals mammal cat1] 

# Method 2 (Risky) 
proc foo {cfg} { 
    proc dict_append {cfgName} { 
     upvar $cfgName cfg 
     dict with cfg animals mammal { 
      append cat1 "hihi" 
     } 
     return $cfg 
    } 
    puts [dict_append cfg] 
} 
foo $cfg 

上面的代碼輸出:

meyaO1hihi 
missing value to go with key 
    while executing 
"dict with cfg animals mammal { 
         append cat1 "hihi" 
       }" 
    (procedure "dict_append" line 3) 
    invoked from within 
"dict_append cfg" 
    (procedure "foo" line 9) 
    invoked from within 
"foo $cfg" 
    (file "basics.tcl" line 20) 

你知道的,這也是一個安全整潔的方式?


編輯#1,2014年2月27日09:15 UTC:
應對@Donal研究員答案:

什麼您的意思是「你不能這樣做.. 。特定格式)「
我認爲我可以選擇鍵是否將被格式化或結構化......這裏有一個例子:

puts {Structured key:} 
dict set cfg animals mammal cat1 meyaO1 
dict set cfg animals mammal cat2 meyaO2 
dict set cfg animals mammal cfg bar 
puts $cfg 
unset cfg 
puts {Formatted key (NOT structured):} 
dict set cfg "animals mammal cat1" meyaO1 
dict set cfg "animals mammal cat2" meyaO2 
dict set cfg "animals mammal cfg" bar 
puts $cfg 

上面的代碼輸出:

Structured key: 
animals {mammal {cat1 meyaO1 cat2 meyaO2 cfg bar}} 
Formatted key (NOT structured): 
{animals mammal cat1} meyaO1 {animals mammal cat2} meyaO2 {animals mammal cfg} bar 

回答

2

這是相當深的。您可能最好使用嵌套dict update s。

# Map the value for the 'animals' key as the 'outer' var 
dict update cfg animals outer { 
    # Map the value for the 'mammal' key as the 'inner' var 
    dict update outer mammal inner { 
     dict lappend inner cat1 "hihi" 
    } 
} 

你不能這樣做這樣的結構鍵,因爲詞典的設計允許任意字符串作爲鍵(和結構化的鍵無法與工作,因爲沒有辦法知道是否a b c,或者甚至是a.b.c,是特定格式的結構化密鑰或密鑰)。

dict with命令旨在用於密鑰更爲人所知的情況。

+0

請參閱我的1st編輯,Thx! – Dor

+1

@Dor:字典允許您使用_any_值作爲關鍵字。如果你想使用列表並解釋它們,那絕對沒問題。在處理這些字典時,您可能不想使用'dict with'。 (當我將任何值作爲關鍵字時,我的意思是它。二進制blob?當然,儘管你可能想避免使用真正大的鍵,但它們可以工作,但可能會減慢一些。 –