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
  • 42,725
  • 12
  • 101
  • 98
user462455
  • 12,838
  • 18
  • 65
  • 96
  • First one warning - using Python reserved words for variable names is dangerous, in your case you use `dict`. I usually use `dct` for this purpose. – Jan Vlcinsky Apr 25 '14 at 18:10
  • `while (dimensions): dict = dict[dimensions.pop(0)]` <-- 3 caveats: 1. Don't name it `dict`, 2. It's more efficient if `dimensions` comes in reversed order (so you can use `pop` not `pop(0)`), 3. don't use your only copy of `dict` since this will change it. – Two-Bit Alchemist Apr 25 '14 at 18:14

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
  • 151,563
  • 33
  • 264
  • 304