Ok, lets say I have a string

str = "main,sub,sub_sub"

how could I use that to edit the value inside the dict

dicx = {'main':{'sub':{'sub_sub':'value to change'}}}

Edited 7 Years Ago by pdxwebdev: n/a

here's a hint

>>>s = "main,sub,sub_sub"
>>>newS = s.split( "," )
>>>newS
[ "main", "sub", "sub_sub" ]

>>>d = { "key":"value" }
>>>d[ "key" ]
"value"

hope this helps :)

Edited 7 Years Ago by masterofpuppets: n/a

That gives me

[ "main", "sub", "sub_sub" ]

but to access sub_sub I need

["main"]["sub"]["sub_sub"]

Edited 7 Years Ago by pdxwebdev: n/a

Here's what I've come up with:

strIds = "main,sub,sub_sub"
dicx = {'main':{'sub':{'sub_sub':'to edit'}}}
str = dicx
for el in strIds.split(","):
	str = str[el]
print(str)

Anything quicker/better looking?

Edited 7 Years Ago by pdxwebdev: n/a

Here's what I don't understand about python:

strIds = "main,sub,sub_sub"
		dicx = {'main':{'sub':{'sub_sub':'to edit'}}}
		print(dicx)
		str = dicx
		for el in strIds.split(","):
			if not el == 'sub_sub':
				str = str[el]
		str[el] = "foo"
		print(dicx)

Outputs:

{'main': {'sub': {'sub_sub': 'to edit'}}}
{'main': {'sub': {'sub_sub': 'foo'}}}

but not this is somehow different when I'm not assigning to array:

strIds = "main,sub,sub_sub"
		dicx = {'main':{'sub':{'sub_sub':'to edit'}}}
		print(dicx)
		str = dicx
		for el in strIds.split(","):
			str = str[el]
		str = "foo"
		print(dicx)

Outputs:

{'main': {'sub': {'sub_sub': 'to edit'}}}
{'main': {'sub': {'sub_sub': 'to edit'}}}

dicx remains unchanged in the second scenario. Any ideas?

Here's what I've come up with:

strIds = "main,sub,sub_sub"
dicx = {'main':{'sub':{'sub_sub':'to edit'}}}
str = dicx
for el in strIds.split(","):
	str = str[el]
print(str)

Anything quicker/better looking?

well you could do it this way also:

strIds = "main,sub,sub_sub"
dicx = {'main':{'sub':{'sub_sub':'to edit'}}}
strIds = strIds.split( "," )
print dicx[ strIds[ 0 ] ][ strIds[ 1 ] ][ strIds[ 2 ] ]

it's shorter but not that effective. I prefer your way, i.e. with the for loop :)

This article has been dead for over six months. Start a new discussion instead.