Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading