I have the following json object:
[{
'firstname': 'Jimmie',
'lastname': 'Barninger',
'zip_code': 12345,
'colors': ['2014-01-01', '2015-01-01'],
'ids': {
'44': 'OK',
'51': 'OK'
},
'address': {
'state': 'MI',
'town': 'Dearborn'
},
'other': {
'ids': {
'1': 'OK',
'103': 'OK'
},
}
}, {
'firstname': 'John',
'lastname': 'Doe',
'zip_code': 90027,
'colors': None,
'ids': {
'91': 'OK',
'103': 'OK'
},
'address': {
'state': 'CA',
'town': 'Los Angeles'
},
'other': {
'ids': {
'91': 'OK',
'103': 'OK'
},
}
}]
I would like to be able to get the number of unique key values that each dict has. In the above, the number would be:
address: 2 # ['state', 'town']
ids: 4 # ['44', '51', '91', '103']
other.ids 3 # ['1', '103', '91']
I've been having trouble iterating of the objects to figure this out, especially if there is an item within a list. What I've been trying thus far is something like the below, though it doesn't currently work I'm pasting it for reference:
def count_per_key(obj, _c=None):
if _c is None: unique_values_per_key = {}
if isinstance(obj, list):
return [count_per_key(l) for l in obj]
elif not isinstance(obj, dict):
pass
else:
for key, value in obj.items():
if not isinstance(value, dict):
continue
elif isinstance(value, dict):
if key not in unique_values_per_key: unique_values_per_key[key] = set()
unique_values_per_key[key].union(set(value.keys()))
return count_per_key(value)
elif isinstance(value, list):
return [count_per_key(o) for o in value]
return unique_values_per_key