我的输入是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']}]}
我试着得到这样的输出:
{"str": 30, "dict": 6, "list": 4, "int": 3, "float": 1}
下面的代码给我:{'str': 8, 'int': 3, 'float': 1}
.我该怎么解决这个问题?
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)))
1条答案
按热度按时间uinbv5nw1#
您可以尝试:
图纸: