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'}}}

Recommended Answers

All 5 Replies

Member Avatar for masterofpuppets

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 :)

That gives me

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

but to access sub_sub I need

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

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?

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?

Member Avatar for masterofpuppets

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.