Python:将字符串转换为代码

时间:2016-03-20 23:48:32

标签: python dictionary eval

如果我有以下字典:

foo = {'bar': {'baz': {'qux': 'gap'} } }

我希望用户能够输入"''' baz'' qux'' dop&#39 ;" [扩展:" '杆' ,' baz' ,' qux' ,' dop' "]转换:

{'qux': 'gap'}

{'qux': 'dop'}

我希望通过以下方式将用户输入转换为字典查找语句(不确定的确切术语)来解决这个问题:

objectPath = "foo"
objectPathList = commandList[:-1]  # commandList is the user input converted to a list

for i in objectPathList:
    objectPath += "[" + i + "]"

changeTo = commandList[-1]

上面的内容使objectPath =" foo [' bar'] [' baz'] [' qux']"和changeTo =' dop'

大!但是,现在我遇到了将该语句转换为代码的问题。我认为eval()可以做到这一点,但是以下似乎不起作用:

eval(objectPath) = changeTo

如何将字符串objectPath转换为替换硬编码?

1 个答案:

答案 0 :(得分:1)

我做这样的事情

foo = {'bar': {'baz': {'qux': 'gap'}}}
input = "'bar','baz','qux','dop'"

# Split the input into words and remove the quotes
words = [w.strip("'") for w in input.split(',')]

# Pop the last word (the new value) off of the list
new_val = words.pop()

# Get a reference to the inner dictionary ({'qux': 'gap'})
inner_dict = foo
for key in words[:-1]:
    inner_dict = inner_dict[key]

# assign the new value
inner_dict[words[-1]] = new_val

print("After:", foo)