I want to create a Python script that takes in a string representation of a dictionary and outputs a list of tuples representing the items of the dictionary. The rub is, I want it to take in variables that have not been defined. An example illustrates this best:
Input: {'test': test}
Output: [('test': test)]
I've created some code to read in the dictionary and define the variables that haven't yet been defined, but when I eval()
the result, it substitutes in the actual value of the variable rather than the variable name.
Here is the code:
import sys
import re
if __name__ == "__main__":
instr = sys.argv[1]
success = False
while not success:
try:
indict = eval(instr)
success = True
except NameError, e:
defname = re.search("name '([^\']*)' is not defined", str(e))
locals()[defname.group(1)] = 0
print indict
I was hoping, for the above defined input value, that the dict it printed out would match the input string perfectly, but instead it has substituted in the value of 0 for test
. Thus the script prints out:
{'test': 0}
I have tried ast.literal_eval
, but it throws a ValueError: malformed string
for any variable name in the literal, even if it's been defined.
Thus, my question is: Is there a way to convert the input dictionary without losing the variable names?