Skip to content

Instantly share code, notes, and snippets.

@Cediddi
Created May 31, 2017 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cediddi/000a4acb15f73e27ddba63d926cecb42 to your computer and use it in GitHub Desktop.
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.
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