1
我正在尋找一種方式將一個字符串追加到內部字典中的現有成員(TCL8.5)整齊地修改內部字典中的一員
- 使用
dict append
沒有好 - 只有1能使遞歸水平。 - 我想出了
dict set
和dict 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
請參閱我的1st編輯,Thx! – Dor
@Dor:字典允許您使用_any_值作爲關鍵字。如果你想使用列表並解釋它們,那絕對沒問題。在處理這些字典時,您可能不想使用'dict with'。 (當我將任何值作爲關鍵字時,我的意思是它。二進制blob?當然,儘管你可能想避免使用真正大的鍵,但它們可以工作,但可能會減慢一些。 –