My input is this json:
object = {'name': 'John',
'age': 30,
'address': {'street': '123 Main St',
'city': 'Sampletown',
'zipcode': '12345',
'frequency': 12.55},
'interests': ['Python programming',
{'hobbies': ['Playing chess',
{'outdoor': {'activity1': 'Hiking', 'activity2': 'Cycling'}}]}],
'friends': [{'name': 'Alice', 'age': 28},
{'name': 'Bob', 'age': 32, 'hobbies': ['Hiking', 'Reading']}]}
And I’m trying to get this kind of output :
{"str": 30, "dict": 6, "list": 4, "int": 3, "float": 1}
My code below gives me: {'str': 8, 'int': 3, 'float': 1}
. How can I fix that?
from collections import Counter
def get_the_type(o):
for key,val in o.items():
if not isinstance(val, (list, dict)):
yield type(val).__name__
elif isinstance(val, list):
for v in val:
if isinstance(v, dict):
yield from get_the_type(v)
else:
yield from get_the_type(val)
final_dict = dict(Counter(get_the_type(object)))
>Solution :
You can try:
obj = {
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Sampletown",
"zipcode": "12345",
"frequency": 12.55,
},
"interests": [
"Python programming",
{
"hobbies": [
"Playing chess",
{"outdoor": {"activity1": "Hiking", "activity2": "Cycling"}},
]
},
],
"friends": [
{"name": "Alice", "age": 28},
{"name": "Bob", "age": 32, "hobbies": ["Hiking", "Reading"]},
],
}
from collections import Counter
def count(o):
yield type(o).__name__
if isinstance(o, dict):
for k, v in o.items():
yield type(k).__name__
yield from count(v)
elif isinstance(o, (list, tuple)):
for v in o:
yield from count(v)
c = Counter(count(obj))
# exclude type of the whole object (optional):
# c[type(obj).__name__] -= 1
print(c)
Prints:
Counter({'str': 30, 'dict': 7, 'list': 4, 'int': 3, 'float': 1})