I have a following dictionary:
JavaScript
x
2
1
pokus = {1 : {"ahoj" : [{"visit" : [0, 0, 0]}]}}
2
Lets suppose I would like to print a value using print(pokus[1]["ahoj"][0]["visit"][0])
. But I nedd [1]["ahoj"][0]["visit"][0]
to be in an extra variable. I try this:
JavaScript
1
6
1
pokus = {1 : {"ahoj" : [{"visit" : [0, 0, 0]}]}}
2
3
insert = [1]["ahoj"][0]["visit"][0]
4
5
print(pokus[insert])
6
But I get an error TypeError: list indices must be integers or slices, not str
. Is there a way how to do that in Python? Thanks
Advertisement
Answer
You cannot do this with an extra variable alone, you need to use a function, e.g.:
JavaScript
1
5
1
def deep_at(obj, indices):
2
for index in indices:
3
obj = obj[index]
4
return obj
5
With variables from your question:
JavaScript
1
6
1
pokus = {1 : {"ahoj" : [{"visit" : [0, 0, 0]}]}}
2
insert = [1, "ahoj", 0, "visit", 0]
3
4
deep_at(pokus, insert) == pokus[1]["ahoj"][0]["visit"][0]
5
# True
6