Skip to content
Advertisement

How to access a multiple dictionary in python?

I have a following dictionary:

pokus = {1 : {"ahoj" : [{"visit" : [0, 0, 0]}]}}

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:

pokus = {1 : {"ahoj" : [{"visit" : [0, 0, 0]}]}}

insert = [1]["ahoj"][0]["visit"][0]

print(pokus[insert])

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

def deep_at(obj, indices):
    for index in indices:
        obj = obj[index]
    return obj

With variables from your question:

pokus = {1 : {"ahoj" : [{"visit" : [0, 0, 0]}]}}
insert = [1, "ahoj", 0, "visit", 0]

deep_at(pokus, insert) == pokus[1]["ahoj"][0]["visit"][0]
# True
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement