Last active
May 21, 2018 10:30
-
-
Save barrucadu/44ae950615518bd93aa4004723fb2148 to your computer and use it in GitHub Desktop.
This file contains 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
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