-5
a=["a",["b",["c","d","e"],"f","g"],"h","j"]
b=a
index=[1,1,1]
for c in index:
  b=b[c]
print("Value: "+b.__str__())
#Code for change value to "k"
print(a)#result is ["a",["b",["c","k","e"],"f","g"],"h","j"]

In there I can get value but I want change it to another.

yourDict[1][1][1] = "test"

Not like this. Index must came from an array.

  • 1
    possible duplicate of [Convert list of positions \[4, 1, 2\] of arbitrary length to an index for a nested list](http://stackoverflow.com/questions/6558365/convert-list-of-positions-4-1-2-of-arbitrary-length-to-an-index-for-a-nested) – Ignacio Vazquez-Abrams Aug 14 '12 at 19:00
  • please read the faq before asking questions. – devsnd Aug 14 '12 at 19:03

1 Answers1

0
yourDict['b']['d']['b'] = "test"

edit -- OP mentions that this is not acceptable because the index must come from a runtime-defined list of arbitrary length.

Solution:

reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"

Demo:

>>> yourDict = {'a':1, 'b':{'c':1, 'd': {'b':1}}}
>>> indexList = ['b','d','b']

>>> reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"
>>> yourDict
{'a': 1, 'b': {'c': 1, 'd': {'b': 'test'}}}

Demo 2:

>>> yourDict = {'a':1, 'b':{'c':1, 'd': {'b':1}}}
>>> indexList=['a']

>>> reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"
>>> yourDict
{'a': 'test', 'b': {'c': 1, 'd': {'b': 1}}}
ninjagecko
  • 88,546
  • 24
  • 137
  • 145