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

问题描述 投票:0回答:1

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

[我已经看到一些人使用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"}

说明应与以下字典相对应;

  • 说明->测试
  • 描述1->嵌套
  • 描述2->字典

代码:

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']) 

结果---> {'':“嵌套”,'1':“嵌套1”,'2':“嵌套”}

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

python-3.x dictionary exec
1个回答
1
投票

我不清楚您要做什么。但是通常为此任务,人们使用JSON:

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

有帮助吗?

© www.soinside.com 2019 - 2024. All rights reserved.