生成任意数量的 if 语句和字典索引

Produce any number of if statements and dictionary indexes

我有问题。如何执行多个 if 语句同时更改字典索引的数量?我认为我的代码很好地总结了我想要发生的事情,但我会进一步解释。使用 dict = {"Hi":{"Hello":{"Greetings":"Goodbye"}}} 我希望一组 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"}}}}

我在 运行 我的示例中遇到错误,但我认为它很好地表达了这一点。

这是您更正后的代码:

    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() 但你将其指定为字符串。

此任务不需要任何 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 语法,但也许那应该是伪代码。