如何将字典值从字符串转换为变量并作为嵌套字典访问?

How to convert dictionary values from string to variable and access as nested dictionary?

是否可以将字典值从字符串转换为变量以访问嵌套字典?

我见过一些人使用 exec() 来做常规字典键的例子;但在嵌套字典的情况下还没有看到它。

我的目标是打开文本文件,解析数据并使用文本文件中的信息创建一个字典,这样当有人编辑它时,它会在用户重新启动程序时自动更新,而不必重新创建可执行文件.

material_txt:

#enter descriptions below for main dictionary keys:
'Description'
'Description1'
'Description2'

#will be used as nested dictionaries
Test = {'':"Nested_Test", '1':"Nested_Test1", '2': "Nested_Test2"}
Nested = {'':"Nested", '1':"Nested1", '2': "Nested"}
Dictionary= {'':"Nested_Dictionary", '1':"Nested_Dictionary1", '2': "Nested_Dictionary2"}

描述应与字典对应如下;

代码:

descriptionList = []

with open(material_txt,'r') as nested:
    for line in nested.readlines():
        if line.startswith("\'"):
            #works with descriptions from text file
            print("Description:{0}".format(line))
            description = line.lstrip("\'")
            descriptionList .append(description.rstrip("\'\n"))
        elif line.startswith("#"):
            print("Comment:{0}".format(line))
            pass
        elif line.startswith("\n"):
            print("NewLine:{0}".format(line))
            pass
        else:
            # This works with nested dictionaries from the text file
            line.rstrip()
            dictionaryInfo = line.split("=")
            #Line below - dictionaryInfo[0] should be variable and not a string
            #exec("dictionary[dictionaryInfo[0]] = eval(dictionaryInfo[1])")
            dictionary[dictionaryInfo[0]] = eval(dictionaryInfo[1])

for descriptions,dictionaries in zip(descriptionList,dictionary.items()):
    #nested dictionary
    mainDictionary[descriptions] = dictionaries[0]

所以当我在下面调用时,我得到了所需的嵌套字典:

print(mainDictionary ['Description1']) 

result ---> {'':"Nested", '1':"Nested1", '2': "Nested"}

我知道我可以 运行 将文本文件作为 python 模块,但我宁愿将其保留为文本文件并在我的程序中进行解析。

我不太清楚你要做什么。但通常对于这个任务人们使用 JSON:

>>> import json
>>> main_dict = json.loads('{"outer1": {"inner1a": 7, "inner1b": 9}, "outer2": 42}')
>>> main_dict
{'outer2': 42, 'outer1': {'inner1b': 9, 'inner1a': 7}}

这有帮助吗?