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

时间:2017-11-25 14:24:21

标签: python python-3.x dictionary if-statement redundancy

我有问题。如何执行一些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"}}}}

我在运行我的示例时遇到了错误,但我认为它可以解决问题。

2 个答案:

答案 0 :(得分: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语法,但也许这应该是伪代码。

答案 1 :(得分: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(),但您已将其指定为字符串。