我遇到問題。我如何執行一些if語句,同時也改變字典索引的數量?我認爲我的代碼總結了我想要發生的事情,但我會進一步解釋。與dict = {"Hi":{"Hello":{"Greetings":"Goodbye"}}}
我想要一組if語句能夠訪問此字典中的每個點,而無需單獨輸入每個點。 所以這一個,生成任意數量的if語句和字典索引
If level == 1:
print(dict["Hi"])
If level == 2:
print(dict["Hi"]["Hello"])
If level == 3:
print(dict["Hi"]["Hello"]["Greetings"])
一段示例代碼:
E = {"C:":{"Desktop.fld":{"Hello.txt":{"Content":"Hello, World"}}}}
def PATH_APPEND(path, item, location, content):
if len(location) == 1:
E[location[0]] = item
E[location[0]][item] = content
if len(location) == 2:
E[location[0]][location[1]] = item
E[location[0]][location[1]][item] = content
if len(location) == 3:
E[location[0]][location[1]][location[2]][item] = content
# ... and so on
PATH_APPEND(E, "Hi.txt", ["C:","Desktop.fld"], "Hi There, World")
print(E)
#{"C:":{"Desktop.fld":{ ... , "Hi.txt":{"Content":"Hi There, World"}}}}
我跑我的例子,而得到一個錯誤,但我認爲它得到跨細點。
我從來不知道在語法之外有Python的語法,我會研究它。我聽說過蛇案,但我認爲這是個人喜好的事情。另外我想我確實忘記了如果小寫。不過謝謝,這個工程很棒! – CoderBoy