0

I have a multidimensional dictionary. List of dimensions is given as a variable. How do I use all the dimensions in that list and access the value stored at the end.

def get_value(dict, dimensions):
    """
    dict is the multidimensional dict
    dimensions is a list of strings which specify all the dimensions
    """

How do I write the below command in a pythonic way

    dict[dimensions[0]][dimensions[1]][dimensions[2]]......[dimensions[len(dimensions)-1]]
Jan Vlcinsky
  • 40,901
  • 12
  • 95
  • 96
user462455
  • 11,838
  • 18
  • 62
  • 94

1 Answers1

2

not too difficult, suppose you wrote this in a slightly different way:

dict = dict[dimensions[0]]
dict = dict[dimensions[1]]
dict = dict[dimensions[2]]
......
dict = dict[dimensions[len(dimensions)-1]]

we see a pattern. Another thing to notice is that we're just iterating through dimensions, we can do this as:

for d in dimensions:
    dict = dict[d]

so, in fact, we can do:

def get_value(mapping, keys):
    for key in keys:
        mapping = mapping[key]
    return mapping

Interestingly, python has a shortcut for this pattern, repeatedly applying an operation to an initial element, one for each element of another sequence, reduce()

def get_value(mapping, keys):
    return reduce(dict.get, keys, mapping)
SingleNegationElimination
  • 144,899
  • 31
  • 254
  • 294