Skip to content

Instantly share code, notes, and snippets.

@mittenchops
Created July 30, 2013 20:45
Show Gist options
  • Save mittenchops/6116758 to your computer and use it in GitHub Desktop.
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.
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