2017-11-25 74 views
2

我遇到問題。我如何執行一些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"}}}} 

我跑我的例子,而得到一個錯誤,但我認爲它得到跨細點。

回答

2

對於此任務,您不需要任何if語句,您可以使用簡單的for循環下降到您的嵌套字典中。

from pprint import pprint 

def path_append(path, item, location, content): 
    for k in location: 
     path = path[k] 
    path[item] = {"Content": content} 

# test 

E = {"C:":{"Desktop.fld":{"Hello.txt":{"Content":"Hello, World"}}}}  
print('old') 
pprint(E) 

path_append(E, "Hi.txt", ["C:", "Desktop.fld"], "Hi There, World") 
print('\nnew') 
pprint(E) 

輸出

old 
{'C:': {'Desktop.fld': {'Hello.txt': {'Content': 'Hello, World'}}}} 

new 
{'C:': {'Desktop.fld': {'Hello.txt': {'Content': 'Hello, World'}, 
         'Hi.txt': {'Content': 'Hi There, World'}}}} 

順便說一句,你不應該使用dict作爲變量名,因爲陰影內置dict類型。

此外,Python中使用小寫字母表示常規變量和函數名稱是常規操作。全部大寫用於常量,大寫名稱用於類。請參閱PEP 8 -- Style Guide for Python Code瞭解更多詳情。

我還注意到,在您的問題開始的代碼塊使用If而不是正確的if語法,但也許這應該是僞代碼。

+0

我從來不知道在語法之外有Python的語法,我會研究它。我聽說過蛇案,但我認爲這是個人喜好的事情。另外我想我確實忘記了如果小寫。不過謝謝,這個工程很棒! – CoderBoy

0

這是你的更正後的代碼:

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) 

你得到一個錯誤,因爲每個級別必須是dict(),但你指定它作爲字符串。