Created
July 30, 2013 20:45
-
-
Save mittenchops/6116758 to your computer and use it in GitHub Desktop.
Count percentage of keys in a weirdly nested json document. Very useful for working with mongodb. Works like variety.js but at the item-level.
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
from __future__ import division | |
from functools import partial | |
def nonemptykeypct(x): | |
""" | |
Returns the percentage of keys that have non-null values in an object (as decimal). | |
Usage: | |
>>> x = {'a': 'meow', 'b': {'c': 'asd'}, 'd': [{'e': 'stuff', 'f': 1}, {'e': 'more stuff', 'f': 2}], 'g': ''} | |
>>> nonemptykeypct(x) | |
0.8571428571428571 | |
""" | |
keys = list(listNkeys(x)) | |
vals = map(partial(getByDot,x),keys) | |
dec = len(filter(None,vals))/len(keys) | |
return(dec) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment