我有一个 json 数据,如:{'data': [{'shares': {'count': 4}, 'id':'226196778181357_353462548788112'}, {'shares': {'count': 5}, 'id': '226196778181357_353075852160115'}, {'shares': {'count': 47}, 'id': '226196778181357_350624229071944'}, {'shares': {'count': 3}, 'id': '226196778181357_350028335798200'}, {'shares': {'count': 5}, 'id': '226196778181357_349395549194812'}, {'shares': {'count': 6}, 'id': '226196778181357_348637945937239'}, {'shares': {'count': 3}, 'id': '226196778181357_342294163238284'}, {'id': '226196778181357_341686736632360'}, {'shares': {'count': 1}, 'id': '226196778181357_341024573365243'}, {'shares': {'count': 9}, 'id': '226196778181357_339828576818176'}, {'shares': {'count': 5}, 'id': '226196778181357_338017080332659'}, {'shares': {'count': 10}, 'id': '226196778181357_337493103718390'}, {'shares': {'count': 1}, 'id': '226196778181357_337432203724480'}, {'shares': {'count': 12}, 'id': '226196778181357_336955527105481'}, {'shares': {'count': 7}, 'id': '226196778181357_335994360534931'}, {'shares': {'count': 11}, 'id': '226196778181357_335979820536385'}, {'shares': {'count': 7}, 'id': '226196778181357_333787794088921'}, {'shares': {'count': 5}, 'id': '226196778181357_333174720816895'}, {'shares': {'count': 14}, 'id': '226196778181357_332554220878945'}]}如果不存在,我想在数据中搜索 dict key ={'shares'} 然后添加一个默认的 dict 即 'shares': {'count': 0}最终输出将如下所示:{'data': [{'shares': {'count': 4}, 'id':'226196778181357_353462548788112'},{'shares': {'count': 5}, 'id': '226196778181357_353075852160115'},{'shares': {'count': 47}, 'id': '226196778181357_350624229071944'},{'shares': {'count': 3}, 'id': '226196778181357_350028335798200'},{'shares': {'count': 5}, 'id': '226196778181357_349395549194812'},
2 回答
长风秋雁
TA贡献1757条经验 获得超7个赞
试试这个:
for e in j['data']:
if not 'shares' in e:
e['shares'] = {'count': 0}
j是json.loads(your_json)。
临摹微笑
TA贡献1982条经验 获得超2个赞
你可以试试这个
dict_list = [{},{'id':12344},{'shares':{'count':1}, 'id':23456}]
for entry in dict_list:
if 'shares' not in entry.keys():
entry['shares']={'count':0}
输出:[{'shares': {'count': 0}}, {'id': 12344, 'shares': {'count': 0}}, {'shares': {'count': 1}, 'id':23456}]
添加回答
举报
0/150
提交
取消