Skip to content

Instantly share code, notes, and snippets.

@brunomlopes
Last active October 15, 2019 15:03
Show Gist options
  • Save brunomlopes/a82ca2979d8c4fd0317486e4d6546b3c to your computer and use it in GitHub Desktop.
Save brunomlopes/a82ca2979d8c4fd0317486e4d6546b3c to your computer and use it in GitHub Desktop.
A hacky pluck function for python, used to flatten data
def pluck(obj, *keys):
def i(o, k):
if "." in k:
(sub, rest) = k.split('.', 1)
if not sub in o:
return None
val = o[sub]
if isinstance(val, list):
return (k, list(i(x, rest)[1] for x in val))
(_, val) = i(val, rest)
return (k, val)
if k not in o:
return (k, None)
return (k, o[k])
if isinstance(obj, list):
return list(dict(i(o, k) for k in keys) for o in obj)
return dict(i(obj, k) for k in keys)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment