如何从词典列表中获取字典数据

时间:2014-01-20 13:51:45

标签: python for-loop dictionary

考虑以下List of Dictionaries(从数据库中检索):

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-statement放在for循环中,但这不起作用,因为它运行所有条目。

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

4 个答案:

答案 0 :(得分:6)

遗憾的是,您的代码毫无意义。您似乎将一些变量附加到列表中,并使用最新版本重新定义其他变量,而无需实际返回所需的字典。

然而,你真正追求的是具有最大“RESEARCH_to”值的字典。因此,您应该使用密钥max替换所有代码:

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

(另外,请尝试发布您正在使用的语言的有效语法。第一个代码段似乎是Javascript,而不是Python。)

答案 1 :(得分:1)

我认为您正在尝试获取最新教育的数据。您应该使用变量来保存最近的日期,并将其与列表中的条目进行比较。将此作为参考:

max_date = None

for edu in education:
    # this line is for initialization
    if max_date is None:
        max_date = edu["studied_to"]

    # check if we have a recent entry at hand
    if max_date <= edu["studied_to"]:
        max_date = edu["studied_to"]  
        qualification = edu["qualifications"]
        fields_of_study = edu["fields_of_study"]

print max_date
print qualification
print fields_of_study

答案 2 :(得分:0)

对语法进行一些修正:

from operator import itemgetter

from datetime import datetime

education =  [{
    "schools" : "Nelson Mandela Metropolitan University",
    "studied_from" : datetime.strptime("16/1/2012 02:00:00", "%d/%m/%Y %H:%M:%S"),
    "studied_to" : datetime.strptime("25/1/2055 02:00:00", "%d/%m/%Y %H:%M:%S"),
    "qualifications" : "  National Diploma",
    "fields_of_study" : "Industrial engineering"
  }, {
    "schools" : "Massachusetts Institute of Technology",
    "studied_from" : datetime.strptime("16/1/2009 02:00:00", "%d/%m/%Y %H:%M:%S"),
    "studied_to" : datetime.strptime("25/1/2020 02:00:00", "%d/%m/%Y %H:%M:%S"),
    "qualifications" : "B Tech",
    "fields_of_study" : "Information Technology"
  }]

most_recent = max(education, key=itemgetter('studied_to'))

答案 3 :(得分:0)

感谢所有人,您的回答非常有帮助。我接受了Daniel的回答并对其进行了修改:

edu = sorted(education, key=lambda studied_to: studied_to)

现在我可以致电edu[0]来获取最新教育的价值:

>>> edu[0]["studied_to"]
datetime.datetime(2055, 1, 25, 2, 0)
>>> edu[-1]["studied_to"]
datetime.datetime(2020, 1, 25, 2, 0)

无论ed[0]始终是最新的教育。