2014-10-16 15 views
1

我試圖設置一個嵌套字典與指示並在該嵌套字典上循環某個命令。循環嵌套詞典與重複的指示

dictionary = {"item 1":{"subitem 1":"one of one","subitem 2":"two of one"},"item 2":{"subitem 1":"one of two", "subitem 2":"two of two"}} 

第一 「圓」(或第一環路)的輸出應爲:

some.command{input:one of one, output: two of one} 

第二 「輪」 的輸出:

some.command{input:one of two, output:two of two} 

等。我真的想要處理痕跡,只需循環遍歷全部二級字典中的條目將不會執行(因爲有命令必須忽略的條目)。循環應該是這個樣子:

for x in dictionary.itervalues(): 
    for y in x.itervalues(): 
     some.command(input: y["subitem 1], output: y["subitem 2"]) 

這在某種程度上是不行的,因爲我不能得到通過索引訪問選定的值。如果我將「some.command」替換爲「print y [」subitem 1「],我得到錯誤」TypeError:字符串索引必須是整數,而不是str「。

我在做什麼錯了?字典了錯誤的方式或我的循環命令或兩者

回答

1

x已經是你的嵌套的字典;你不需要你的內循環,而不是使用x(一個沒有意義的名字),我用nested_dict澄清你的循環正在迭代:

for nested_dict in dictionary.itervalues(): 
    some.command(input=nested_dict["subitem 1"], output=nested_dict["subitem 2"]) 

你的內部循環然後循環了那些嵌套的dic tionaries; y綁定到"one of one",然後"two of one"等嘗試使用y['some string']試圖將索引應用於這些字符串。

此外,在這些for循環中無處是使用索引的Python。 Python for循環迭代直接覆蓋項目。您要讓Python循環遍歷dictionary.itervalues(),因此每個nested_dict都綁定到每個值dictionary。沒有索引被使用。

+0

Woah非常棒,謝謝!我缺乏聲望來投票你的答案,但我肯定會這樣做:-) – Ratnanil 2014-10-16 18:40:32