从JSON词典中提取组件



我有一个JSON字典(result_dict_tag),如下所示:

{'10644906845': {'photo': {'id': '10644906845',
   'tags': {'tag': [{'_content': 'srilanka',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-23098',
      'machine_tag': 0,
      'raw': 'sri lanka'},
     {'_content': 'navy',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-7137',
      'machine_tag': 0,
      'raw': 'navy'},
     {'_content': 'vessel',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-8792',
      'machine_tag': 0,
      'raw': 'vessel'}]}},
  'stat': 'ok'},
      '11778819726': {'photo': {'id': '11778819726',
   'tags': {'tag': [{'_content': 'sri',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12165',
      'machine_tag': 0,
      'raw': 'sri'},
     {'_content': 'lanka',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12166',
      'machine_tag': 0,
      'raw': 'lanka'},
     {'_content': 'mirissa',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-1158107',
      'machine_tag': 0,
      'raw': 'mirissa'}]}},
  'stat': 'ok'}}

我想要的是从每个字典(例如result_dict_tag['10644906845']['photo']["tags"]['tag'][0]['raw'])中提取"原始"单词,并为每个用户创建一个构成用户ID和相关原始单词的数据框架。我觉得这需要一些循环。我已经写了一个,它仅导致仅与第一个用户相关的"原始"单词。我经历了与此相似的文档和各种问题。但无法弄清楚。任何帮助都将受到赞赏。

您可以在单个列表中提取它们

raw_words = [mydict[i]['photo']["tags"]['tag'][k]['raw']
             for k in range(len(mydict[i]['photo']["tags"]['tag']))
             for i in mydict]
print(raw_words)
>> ['sri', 'sri lanka', 'lanka', 'navy', 'mirissa', 'vessel']

如果我正确理解了您,则您想要的是dictslist,每个dict包含idrow

在您的dict下方添加这些代码行:

new_list = result_dict_tag['10644906845']['photo']["tags"]['tag']
new_desired_list = []
for index in range(len(new_list)):
  tempDict = {} 
  for key in new_list[index]:
      if(key=='id'):
          tempDict['id'] = new_list[index][key]
      if(key=='raw'):
          tempDict['row'] = new_list[index][key]
  new_desired_list.append(tempDict)
print(new_desired_list)

最新更新