Python-遍历嵌套字典和获取值

时间:2020-04-05 19:49:27

标签: python list dictionary

列表中的嵌套字典格式相同。我试图遍历每个元素,并找到summary的值为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返回summary的次数为2,并且由于已分配了这两个不同的人,因此受让人的值为Mark and Scott

2 个答案:

答案 0 :(得分:1)

您可以循环浏览列表。这是我的示例:

data = [{'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'}]}]
people = [sum["assignees"][0]["summary"] for sum in data if "through the API" in sum["summary"]]   #This will return ["Mark", "Scott"]
number_of_assignees = len(people)    #This will return 2

答案 1 :(得分:1)

制作一个熊猫数据框:

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])])