Skip to content

Instantly share code, notes, and snippets.

@barrucadu
Last active May 21, 2018 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save barrucadu/44ae950615518bd93aa4004723fb2148 to your computer and use it in GitHub Desktop.
Save barrucadu/44ae950615518bd93aa4004723fb2148 to your computer and use it in GitHub Desktop.
def get(path, default=None):
"""Look up a path in a dictionary, returning the default value if any
link is missing.
"""
def go(d):
for step in path:
try:
d = d[step]
except (KeyError, TypeError) as e:
return default
return d
return go
def uniques(source, fmap=lambda x: x, restrictOn=lambda x: x, discard=lambda x: x is None):
"""Map a function over an iterable, yielding elements which are unique
according to the given restriction function and which do not match
the discard function.
"""
seen = set()
for thing in source:
thing = fmap(thing)
if discard(thing):
continue
if restrictOn(thing) in seen:
continue
seen.add(restrictOn(thing))
yield thing
# example usage:
# with open(jsonfile) as f:
# data = json.load(f)
# for fields in functions.uniques(
# data['hits']['hits'],
# fmap=functions.get(['_source', '@fields']),
# restrictOn=functions.get(['path'])):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment