2017-11-25 79 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(),但你指定它作为字符串。