2016-03-20 34 views
1

Aşağıdaki sözlüğü varsa:Python: kodlamak dize dönüştürme

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

Ben kullanıcı " 'bar', 'Baz', 'qux', 'dop'" [girişine mümkün istiyorum genişletme: " 'bar', 'baz', 'qux', 'dop'"] dönüştürmek için:

{'qux': 'gap'} 

{'qux': 'dop'} 

için bu yaklaşım umuyordum için kullanıcı girişi dönüştürerek sözlük-arama-stateme Aşağıdaki aracılığıyla nt (tam terimi emin):

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

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

changeTo = commandList[-1] 

yukarıda objectPath = "fon [ 'bar'] [ 'baz'] [ 'qux']" ve changeTo = 'dop'

yapar

Harika! Ancak, şimdi bu ifadeyi kod haline getirerek sorunlarım var.

eval(objectPath) = changeTo 

nasıl sert yazılı kodunu değiştirmek için dize objectPath dönüştürebilirsiniz: Ben, ancak aşağıdaki çalışmamasına görünüyor hile yapacağını eval() düşünce?

+2

'eval (objectPath + "= '" + changeTo "'") gibi bir şey yapardım' L3viathan @ – L3viathan

+0

inanamıyorum Bunu kaçırdım! Teşekkürler! – Jack

cevap

1

Bu

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)