Skip to content

Instantly share code, notes, and snippets.

@nijave
Created May 19, 2020 14:05
Show Gist options
  • Save nijave/c242d8167c32480347aef8c1d07b86fd to your computer and use it in GitHub Desktop.
Save nijave/c242d8167c32480347aef8c1d07b86fd to your computer and use it in GitHub Desktop.
Python helper functions
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