recursion - recursive itemgetter for python -


this question has answer here:

is there recursive itemgetter in python. let's have object

d = {'a': (1,2,3), 'b': {1: (5,6)}} 

and wanted first element of tuple d['a']? far can tell itemgetter 1 level, i.e. me a or b or both.

is there clever way of combining itertools itemgetter produce desired result.

so want able call

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 

i don't 'clever' ways. obvious better.

you can write getter iterates along list of subscripts:

def getter(x, *args):   p = x   s in args:     p = p[s]   return p  >>> d = {'a': (1,2,3), 'b': {1: (5,6)}} >>> getter( d, 'a', 0) 1 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -