recursive itemgetter for python
python, recursion
Solution
I don't like 'clever' ways. Obvious is better.
You can very easily write a getter that iterates along a list of subscripts:
def getter(x, *args):
for k in args:
x = x[k]
return x
>>> d = {'a': (1,2,3), 'b': {1: (5,6)}}
>>> getter(d, 'a', 0)
1
Problem
Is there a recursive `itemgetter` in python. Let's say you have an object like ``` d = {'a': (1,2,3), 'b': {1: (5,6)}} ``` and I wanted to get the first element of the tuple from `d['a']`? As far as I can tell `itemgetter` will only do one level, i.e. get me `a` or `b` or both. Is there some clever way of combining `itertools` with `itemgetter` to produce the desired result. So basically what I want to be able to call is ``` from operator import itemgetter d = {'a': (1,2), 'b': (4, (5,))} itemgetter({'a': 0})(d) --> 1 itemgetter({'b': 0})(d) --> 4 itemgetter({'b': {1: 0}})(d) --> 5 d = {'a': {'b': (1,2,3)}} itemgetter({'a': {'b': 2}})(d) --> 3 ```