Created
May 19, 2020 14:05
-
-
Save nijave/c242d8167c32480347aef8c1d07b86fd to your computer and use it in GitHub Desktop.
Python helper functions
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 find(func, i): | |
""" | |
Finds the first match in an iterable | |
Works like `filter` but returns a single item | |
""" | |
try: | |
return next(filter(func, i)) | |
except StopIterator: | |
raise ValueError("No matching item found") | |
def flatten(i, key=None): | |
""" | |
Convert an iterable `i` of dictionaries | |
with key `key` of lists to a list | |
i.e. [{'a': [1,2]}, {'a': [3,4]}] -> [1,2,3,4] | |
""" | |
i = iter(i) | |
first = next(i) | |
if key is None: | |
key = next(iter(first.keys())) | |
items = first[key] | |
for item in i: | |
items.extend(item[key]) | |
return items |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment