Home > Mobile >  How to access a multiple dictionary in python?
How to access a multiple dictionary in python?

Time:08-11

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  • Related