pythonpython-3.xdictionaryexec

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


Is it possible to convert dictionary values from string to a variable to access the nested dictionary?

I've seen some instances where people are using exec() to do regular dictionaries keys; but have not seen it in cases of nested dictionary.

My goal is to open text file, parse the data and create a single dictionary with the info from the text file, so that when someone edits it, it will automatically update when user restarts program instead of having to recreate executable.

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"}

The descriptions should correspond to the dictionaries as follows;

Code:

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]

so when I call below I get the desired nested dictionary:

print(mainDictionary ['Description1']) 

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

I'm aware I could run the text file as a python module, but I would rather just leave it as a text file and do parsing in my program.


Solution

  • It's not exactly clear to me what you are trying to do. But usually for this task people use JSON:

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

    Does this help?