Python 如何从字典的字典列表中提取元素

Python 如何从字典的字典列表中提取元素,python,dictionary,Python,Dictionary,我有一本字典,下面是弹性搜索 我需要提取一些元素并添加到列表中 代码如下 import json import pprint def details(searchtest): response = [] for each in searchtest: course = { 'name': each['_source']['name'], 'proffesor':[]} for p

我有一本字典,下面是弹性搜索

我需要提取一些元素并添加到列表中

代码如下

import json
import pprint


def details(searchtest):
    response = []
    for each in searchtest:
        course = {
            'name': each['_source']['name'],
            'proffesor':[]}
        
        for prof in each.get('professor', []):
            course['proffesor'].append(prof['_source']['name'])
            course['proffesor'].append(prof['_source']['department'])
        response.append(course)
    return response

if __name__ == "__main__":
    import pprint
    pp = pprint.PrettyPrinter(4)
    pp.pprint(details(searchtest['hits']['hits']))
我的输出

[   {'name': 'Cost Accounting 400', 'proffesor': []},
    {'name': 'Computer Internals 250', 'proffesor': []},
    {'name': 'Accounting Info Systems 350', 'proffesor': []},
    {'name': 'Tax Accounting 200', 'proffesor': []},
    {'name': 'Capital Markets 350', 'proffesor': []},
    {'name': 'Theatre 410', 'proffesor': []},
    {'name': 'Accounting 101', 'proffesor': []},
    {'name': 'Marketing 101', 'proffesor': []},
    {'name': 'Anthropology 230', 'proffesor': []},
    {'name': 'Computer Science 101', 'proffesor': []}]
我的输出profesor列表是空的。该列表必须填写proffesor.name和proffesor.department 预期输出将包含教授姓名和系的列表

下面是代码中的错误行

import json
import pprint


def details(searchtest):
    response = []
    for each in searchtest:
        course = {
            'name': each['_source']['name'],
            'proffesor':[]}
        
        for prof in each.get('professor', []):
            course['proffesor'].append(prof['_source']['name'])
            course['proffesor'].append(prof['_source']['department'])
        response.append(course)
    return response

if __name__ == "__main__":
    import pprint
    pp = pprint.PrettyPrinter(4)
    pp.pprint(details(searchtest['hits']['hits']))
对于每个项目的教授,获得“教授”[]:

随你的便

In [57]: response = []

In [58]: for search in searchtest:
    ...:     response.append({'name':search["_source"]['name'],'professor':[search["_source"]["professor"]["name"],search["_source"]["professor"]["department"]]})
    ...:

In [59]: response
Out[59]:
[{'name': 'Cost Accounting 400', 'professor': ['Bill Cage', 'accounting']},
 {'name': 'Computer Internals 250',
  'professor': ['Gregg Payne', 'engineering']},
 {'name': 'Accounting Info Systems 350',
  'professor': ['Bill Cage', 'accounting']},
 {'name': 'Tax Accounting 200', 'professor': ['Thomas Baszo', 'finance']},
 {'name': 'Capital Markets 350', 'professor': ['Thomas Baszo', 'finance']},
 {'name': 'Theatre 410', 'professor': ['Sebastian Hern', 'art']},
 {'name': 'Accounting 101', 'professor': ['Thomas Baszo', 'finance']},
 {'name': 'Marketing 101', 'professor': ['William Smith', 'finance']},
 {'name': 'Anthropology 230', 'professor': ['Devin Cranford', 'history']},
 {'name': 'Computer Science 101', 'professor': ['Gregg Payne', 'engineering']}]
使用您的代码: 你不必反复询问教授。这是一本字典,你可以用钥匙直接查到

In [64]: import json
    ...: import pprint
    ...: def details(searchtest):
    ...:     response = []
    ...:     for each in searchtest:
    ...:         course = {
    ...:             'name': each['_source']['name'],
    ...:             'proffesor':[]}
    ...:         prof = each['_source']['professor']
    ...:         course['proffesor'].append(prof['name'])
    ...:         course['proffesor'].append(prof['department'])
    ...:         response.append(course)
    ...:     return response
    ...:
    ...:

In [65]: details(searchtest)
Out[65]:
[{'name': 'Cost Accounting 400', 'proffesor': ['Bill Cage', 'accounting']},
 {'name': 'Computer Internals 250',
  'proffesor': ['Gregg Payne', 'engineering']},
 {'name': 'Accounting Info Systems 350',
  'proffesor': ['Bill Cage', 'accounting']},
 {'name': 'Tax Accounting 200', 'proffesor': ['Thomas Baszo', 'finance']},
 {'name': 'Capital Markets 350', 'proffesor': ['Thomas Baszo', 'finance']},
 {'name': 'Theatre 410', 'proffesor': ['Sebastian Hern', 'art']},
 {'name': 'Accounting 101', 'proffesor': ['Thomas Baszo', 'finance']},
 {'name': 'Marketing 101', 'proffesor': ['William Smith', 'finance']},
 {'name': 'Anthropology 230', 'proffesor': ['Devin Cranford', 'history']},
 {'name': 'Computer Science 101', 'proffesor': ['Gregg Payne', 'engineering']}]
我为响应中的每个项目都添加了无检查。由于_源项检查3次,教授项检查2次,因此可以更有效地执行此操作

def详细信息搜索测试: 响应=[] 对于searchtest中的每一项: 课程={ 名称:each.get_source,{}.getname, 教授:[ each.get_source,{}.getprofessor,{}.getname, each.get_source,{}.getprofessor,{}.getdepartment, ] } 答复:附件课程 返回响应 如果uuuu name uuuuu==\uuuuuuuu main\uuuuuuuu: 导入pprint pp=pprint.PrettyPrinter4 pp.pprintdetailssearchtest
你的教授在每个[_source][proffesor]中,而不是每个[proffesor]@JannesCarpentier我也试过了。是的,你需要在每个[u source][proffesor]中更改教授的名称。getprofessorline@JannesCarpentier先生,我理解代码中的错误。我在每个方面都测试了for prof。获取[_source][proffesor],]。如果each.get_source,{}.getprofessor不是,你能帮我写下确切的syntaxToCheck for None吗None@Nons更新我的回答我完全理解你的代码。我只是想知道如何更新我的每个prof的代码。get'profector',[]:到类似于每个prof的代码。get[_source][profesor],]当我的it抛出错误时,当你循环遍历字典时,你会得到字典的键,你必须使用它来选择值。我不推荐它,除非需要一个大的嵌套字典,我需要写很多条件,比如教授的id是否匹配另一个匹配。所以我写了。获取方法。你能帮我写下for prof中代码的确切语法吗?获取'professor',[]:
In [64]: import json
    ...: import pprint
    ...: def details(searchtest):
    ...:     response = []
    ...:     for each in searchtest:
    ...:         course = {
    ...:             'name': each['_source']['name'],
    ...:             'proffesor':[]}
    ...:         prof = each['_source']['professor']
    ...:         course['proffesor'].append(prof['name'])
    ...:         course['proffesor'].append(prof['department'])
    ...:         response.append(course)
    ...:     return response
    ...:
    ...:

In [65]: details(searchtest)
Out[65]:
[{'name': 'Cost Accounting 400', 'proffesor': ['Bill Cage', 'accounting']},
 {'name': 'Computer Internals 250',
  'proffesor': ['Gregg Payne', 'engineering']},
 {'name': 'Accounting Info Systems 350',
  'proffesor': ['Bill Cage', 'accounting']},
 {'name': 'Tax Accounting 200', 'proffesor': ['Thomas Baszo', 'finance']},
 {'name': 'Capital Markets 350', 'proffesor': ['Thomas Baszo', 'finance']},
 {'name': 'Theatre 410', 'proffesor': ['Sebastian Hern', 'art']},
 {'name': 'Accounting 101', 'proffesor': ['Thomas Baszo', 'finance']},
 {'name': 'Marketing 101', 'proffesor': ['William Smith', 'finance']},
 {'name': 'Anthropology 230', 'proffesor': ['Devin Cranford', 'history']},
 {'name': 'Computer Science 101', 'proffesor': ['Gregg Payne', 'engineering']}]
[   {'name': 'Cost Accounting 400', 'professor': ['Bill Cage', 'accounting']},
    {   'name': 'Computer Internals 250',
        'professor': ['Gregg Payne', 'engineering']},
    {   'name': 'Accounting Info Systems 350',
        'professor': ['Bill Cage', 'accounting']},
    {'name': 'Tax Accounting 200', 'professor': ['Thomas Baszo', 'finance']},
    {'name': 'Capital Markets 350', 'professor': ['Thomas Baszo', 'finance']},
    {'name': 'Theatre 410', 'professor': ['Sebastian Hern', 'art']},
    {'name': 'Accounting 101', 'professor': ['Thomas Baszo', 'finance']},
    {'name': 'Marketing 101', 'professor': ['William Smith', 'finance']},
    {'name': 'Anthropology 230', 'professor': ['Devin Cranford', 'history']},
    {   'name': 'Computer Science 101',
        'professor': ['Gregg Payne', 'engineering']}]