2016-03-20 9 views
1

をコーディングする文字列を変換しますPythonの次の辞書持っている私がいる場合

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

を、私は、ユーザーが入力できるようにしたい「『バー』、 『バズ』、 『qux』、 『DOP』」[拡張: " 'バー'、 'バズ'、 'qux'、 'DOP'"]に変換する:

{'qux': 'gap'} 

{'qux': 'dop'} 

に私はへのユーザ入力を変換することによって、これをアプローチする期待していました辞書ルックアップ・ステートメント以下介してNT(正確な用語の不明):

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 [ 'バー'] [ 'バズ'] [ 'qux']" とchangeToは= 'DOP'

を行います

素晴らしい!しかし、今私はそのステートメントをコードに変えることに問題がありました。

私はハード書かれたコードを置き換えるために、文字列objectPathに変換することができますどのよう
eval(objectPath) = changeTo 

:私は、トリックを行うだろう、しかし、次のように動作しないようです)(evalのを思いましたか?

+2

'evalの(objectPath + "= '" + changeTo "'")' – L3viathan

+0

ような何かをしたいです!ありがとう! – Jack

答えて

1

私はそれを逃した信じることができないL3viathan @この

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) 
関連する問題