Python:将字符串转换为代码

Python:将字符串转换为代码,python,dictionary,eval,Python,Dictionary,Eval,如果我有以下字典: foo = {'bar': {'baz': {'qux': 'gap'} } } 我希望用户能够输入“'bar'、'baz'、'qux'、'dop'”[扩展:“'bar'、'baz'、'qux'、'dop'”]以转换: {'qux': 'gap'} 到 我希望通过以下方式将用户输入转换为字典查找语句(不确定确切的术语)来实现这一点: objectPath = "foo" objectPathList = commandList[:-1] # commandList is

如果我有以下字典:

foo = {'bar': {'baz': {'qux': 'gap'} } }
我希望用户能够输入“'bar'、'baz'、'qux'、'dop'”[扩展:“'bar'、'baz'、'qux'、'dop'”]以转换:

{'qux': 'gap'}

我希望通过以下方式将用户输入转换为字典查找语句(不确定确切的术语)来实现这一点:

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以替换硬代码?

我会这样做

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)

eval(objectPath+“=”+changeTo“”)
@l3via我真不敢相信我错过了!谢谢
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)