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

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

我有一个问题。如何执行多个 if 语句,同时更改字典索引的数量?我认为我的代码很好地总结了我想要发生的事情,但我将进一步解释。 with 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"}}}}

我在运行示例时遇到错误,但我认为它很好地表达了要点。

最佳答案

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

关于python - 生成任意数量的 if 语句和字典索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47487024/

相关文章:

python - 打印链接到列表中键的字典值

python - Django/Travis CI - 配置 .travis YAML 文件以首先启动本地主机服务器,然后在不挂起的情况下运行我的测试?

python - 将 Python 代码转换为符合 PEP8 的工具

python - 如何让 pandas.read_csv() 从 CSV 文件列中推断出 datetime 和 timedelta 类型?

Python configparser 不会接受没有值的键

python - 如何解析 python 中的 requests.session cookie 属性

Python - 列表 : How To Remove Empty Attributes From a List of Dictionaries With Nested Properties?

Swift 按值对字典进行排序

python - 如何从包含列表的嵌套Python字典中的键中删除符号?

python - 在从 Python 调用的 C 函数中使用 PyFloat_FromDouble 时获得错误结果