Created
May 31, 2017 12:05
-
-
Save Cediddi/000a4acb15f73e27ddba63d926cecb42 to your computer and use it in GitHub Desktop.
We all love operator.itemgetter, wouldn't it be cool if you can just do itemgetter("a.b", "a.c"). This works great on nested dictionaries, not so great with sequences.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class nested_itemgetter: | |
def __init__(self, item, *items): | |
if not items: | |
def func(obj): | |
steps = item.split(".") | |
for step in steps: | |
obj = obj[step] | |
return obj | |
self._call = func | |
else: | |
items = (item,) + items | |
def func(obj): | |
rval = [] | |
for _item in items: | |
steps = _item.split(".") | |
for step in steps: | |
obj = obj[step] | |
rval.append(obj) | |
return tuple(rval) | |
self._call = func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment