1

If I have the following dictionary:

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

I want the user to be able to input "'bar','baz','qux','dop'" [expansion: " 'bar' , 'baz ' , 'qux' , 'dop' "] to convert:

{'qux': 'gap'}

to

{'qux': 'dop'}

I was hoping to approach this by converting the user input to a dictionary-lookup-statement (unsure of the exact term) through the following:

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

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

changeTo = commandList[-1]

The above makes objectPath = "foo['bar']['baz']['qux']" and changeTo = 'dop'

Great! However, now I have been having issues with turning that statement into code. I thought eval() would do the trick, however the following seems not to work:

eval(objectPath) = changeTo

How can I convert the string objectPath to replace hard-written code?

2
  • 2
    eval(objectPath + "='" + changeTo "'") Commented Mar 20, 2016 at 23:50
  • @L3viathan I can't believe I missed that! Thanks! Commented Mar 20, 2016 at 23:58

1 Answer 1

1

I'd do something like this

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.