How to access a multiple dictionary in python?

Question:

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

Asked By: vojtam

||

Answers:

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
Answered By: norok2

This doesn’t work with an extra variable.
With insert = [1] you’re creating a new list [1] and since list indices can’t be strings, this throws you the error.

To fix that use a function as @norok2 provided or the even simplier way just remove the extra variable:

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

var = pokus[1]["ahoj"][0]["visit"][0]
print(var)

Output

0
Answered By: puncher

Use of lambda function may be a good alternative.

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

print(desired_value(pokus))
# output: 0
Answered By: Jobo Fernandez
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.