2

So let's say I have a dictionary of form:

d = {'a':{'b':{'c':1,'d':2},'e':1}}

And I wish to fetch an element from this dictionary with keys defined in a list eg:

l = ['a','e'] 

or

l = ['a','b','c']

I could do so with something like:

def getVal(d,keys):
    if keys==[]:
        return d
    else:
        nextD = d[keys.pop(0)]
        return getVal(nextD,keys)

But I'm wondering if there is a more wizardy python way to do it

(something along the lines of val = d[*l] ???)

John Greenall
  • 1,670
  • 11
  • 17

1 Answers1

0

According to the link in Martijn's comment, the answer to this question would be:

def getVal(d,keys):
    return reduce(dict.__getitem__, keys, d)
Timothy
  • 4,467
  • 5
  • 28
  • 51