Python:将字符串转换为cod

2024-04-30 04:07:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有以下词典:

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

我希望用户能够输入“'bar'、'baz'、'qux'、'dop'”[扩展:“'bar'、'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以替换硬编写的代码?你知道吗


Tags: 代码用户fooevalbarbaz语句词典
1条回答
网友
1楼 · 发布于 2024-04-30 04:07:08

我会这样做

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)

相关问题 更多 >