首页 > 解决方案 > Python - 遍历嵌套字典并获取值

问题描述

我在列表中有相同格式的嵌套字典。我正在尝试遍历每个元素并找到我们拥有summaryas值through the API的次数,并计算through the API.

[{'id': '101',
 'type': 'log_file',
 'summary': 'Escalated to Mark through the API',
 'assignees': [{'id': 'xyz',
 'type': 'user_reference',
 'summary': 'Mark'}]},
 {'id': '102',
  'type': 'log_file',
  'summary': 'Escalated to Kevin by SMS',
  'assignees': [{'id': 'abc',
  'type': 'user_reference',
  'summary': 'Kevin'}]},
 {'id': '103',
  'type': 'log_file',
  'summary': 'Escalated to Scott through the API',
  'assignees': [{'id': 'pqr',
  'type': 'user_reference',
  'summary': 'Scott'}]}]

through the API在上面的示例中,我预计返回的次数为 2,并且由于分配了这两个不同的人summary,因此受让人的值是2。Mark and Scott

标签: pythonlistdictionary

解决方案


制作熊猫数据框:

df=pd.DataFrame(dd)

计算出现次数并将受让人姓名放在单独的列中:

df['summary'].str.contains('through the API').sum()
df['names'] = pd.Series([df.iloc[s,3][0]['summary'] for s in np.arange(0,df.shape[0])])

推荐阅读