Reputation: 167
I have a multidimensional dictionary in Python, and I have a list which has the keys that I want to access. What is the easiest way to get the value from the dictionary?
Example:
main = {
'one': {
'two': {
'three': "Final word"
}
}
}
mylist = ['one', 'two', 'three']
# and I want to print out the value of `three` ("Final word")
Upvotes: 3
Views: 222
Reputation: 9753
An equivalent to mhlester's solution, with a taste of functional programming:
import operator
print reduce(operator.getitem, mylist, main)
Upvotes: 3
Reputation: 23231
Loop over mylist
, storing an intermediate dict (I called it submain
) until you run out of mylist
elements:
submain = main
for key in mylist:
submain = submain[key]
print submain
Upvotes: 7