Inazuma
Inazuma

Reputation: 178

Go to dictionary key from list

I have a dictionary tree with a long line of values:

dict = {"a":{"b":{"c":"Hello World!"}}}

And if I wish to print out "Hello World!" From inside the dictionary, I would have to do this:

print(dict["a"]["b"]["c"])

However, I wish to be able to travel through the dictionary by using a list. In theory, this is how it would work:

dict = {"a":{"b":{"c":"Hello World!"}}}
list = ["a", "b", "c"]
print(dict[list])

And python would print "Hello World!", however this doesn't seem to be how it works. Any ideas would be of great help!

Upvotes: 1

Views: 87

Answers (1)

BrenBarn
BrenBarn

Reputation: 251518

You can use reduce (which in Python 3 you need to import with from functools import reduce).

reduce(lambda a, b: a[b], key_list, my_dict)

Like this:

my_dict = {"a":{"b":{"c":"Hello World!"}}}
key_list = ["a", "b", "c"]

>>> reduce(lambda a, b: a[b], key_list, my_dict)
'Hello World!'

An exception will be raised if any of the keys don't exist (or if the dictionary nesting is too "shallow" so that there aren't as many dicts as keys).

Note that I renamed your variables. It's not a good idea to use list and dict as variable names because they shadow the builtin types with those names.

Upvotes: 6

Related Questions