Last active
October 15, 2019 15:03
-
-
Save brunomlopes/a82ca2979d8c4fd0317486e4d6546b3c to your computer and use it in GitHub Desktop.
A hacky pluck function for python, used to flatten data
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 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