Skip to main content
 首页 » 编程设计

python之如何从字典列表中获取字典的数据

2025年05月04日14leader

考虑以下字典列表(从数据库中检索):

education =  [{ 
    "schools" : "Nelson Mandela Metropolitan University", 
    "studied_from" : new Date("16/1/2012 02:00:00"), 
    "studied_to" : new Date("25/1/2055 02:00:00"), 
    "qualifications" : "  National Diploma", 
    "fields_of_study" : "Industrial engineering" 
  }, { 
    "schools" : "Massachusetts Institute of Technology", 
    "studied_from" : new Date("16/1/2009 02:00:00"), 
    "studied_to" : new Date("25/1/2020 02:00:00"), 
    "qualifications" : "B Tech", 
    "fields_of_study" : "Information Technology" 
  }] 

我正在尝试从一个 dict 中获取要返回的数据。
我尝试了以下方法:

   for edu in context.education: 
        studied_to.append(edu.studied_to) 
        qualification = edu.qualifications 
        fields_of_study = edu.fields_of_study 
        school = edu.schools 
        recent = max(studied_to) 
    if recent: 
        print recent 
        print qualification 
        print fields_of_study 

这不起作用,因为它总是返回最后一个 dict 中数据的数据, 我还尝试将 if 语句 放在 for 循环中,但这也不起作用,因为它会针对所有条目运行。

我最终想使用这些值在 HTML 页面上生成。

请您参考如下方法:

不幸的是,您的代码毫无意义。您似乎正在将一些变量附加到列表中,并使用最新版本重新定义其他变量,而没有真正返回您想要的字典。

然而,您实际上想要的似乎是具有最大“studied_to”值的字典。因此,您应该将所有代码替换为 max 和一个键:

most_recent = max(education, key=lambda s: s['studied_to']) 

(此外,请尝试发布适用于您使用的语言的有效语法。第一个片段似乎是 Javascript,而不是 Python。)