【发布时间】:2020-05-19 19:01:41
【问题描述】:
是否可以将字典值从字符串转换为变量以访问嵌套字典?
我见过一些例子,人们使用 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'])
结果 ---> {'':"Nested", '1':"Nested1", '2':"Nested"}
我知道我可以将文本文件作为 python 模块运行,但我宁愿将其保留为文本文件并在我的程序中进行解析。
【问题讨论】:
-
我很确定你会在这里找到答案:stackoverflow.com/questions/14676265/…
-
我很确定您会在这里找到答案:converting text file to array of strings
标签: python-3.x dictionary exec