0
a={'1':{'2':{'3':'4'}}}

for something in range(0,some_input): # a forloop
    print something_x

i need the "print something_x" to be like this ..

for loop1 -> {'2':{'3':'4'}}
for loop2 -> {'3':'4'}
for loop3 -> {'4'}

the something_x has to be a['1'] in loop 1 and a['1']['2'] in loop 2 and so on

the problem is i get a few numbers and one of those numbers tells me which level of hierarchy in the json object i need to replace/edit/add depending on the variable.

i can try creating copy's and then replacing those or try the recursive way but i may get ctrl+c interrupt and don't want to loose the data i have already edited up until now

i also have tried by creating variable name dynamically like

    zzz="a['1']['2']"
    eval(zzz)

i know this is not the best way to do it

is there anyway to dynamically add a key infront of the json object ?

boltsfrombluesky
  • 412
  • 3
  • 12
  • You might want to look at http://stackoverflow.com/questions/3229419/pretty-printing-nested-dictionaries-in-python as well as http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python – Dr. Jan-Philip Gehrcke Mar 14 '13 at 17:47

1 Answers1

0

In your specific example you could use a pointer pointing deeper and deeper into the dict:

In [33]: a = {'1': {'2': {'3': '4'}}}

In [34]: pointer = a

In [35]: for key in range(1, 4):
   ....:     print pointer[str(key)]
   ....:     pointer = pointer[str(key)]
   ....:
{'2': {'3': '4'}}
{'3': '4'}
4

Not sure what the bigger picture is (and what does it have to do with JSON).

Pavel Anossov
  • 54,107
  • 13
  • 131
  • 116