Skip to content
Advertisement

Pass nested dictionary location as parameter in Python

If I have a nested dictionary I can get a key by indexing like so:

JavaScript

Am I able to pass that indexing as a function parameter?

JavaScript

Obviously, this is incorrect, I get TypeError: list indices must be integers, not str.

How can I do it correctly?

Advertisement

Answer

You can use reduce (or functools.reduce in python 3), but that would also require you to pass in a list/tuple of your keys:

JavaScript

(In your case ['a']['b'] doesn’t work because ['a'] is a list, and ['a']['b'] is trying to look up the element at “b“th index of that list)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement