字典与键内的键

时间:2015-12-15 03:18:21

标签: python dictionary

我需要找到一种方法来返回键中的第一个值' hw'对于键1和键2并求它们但是我想不出办法。它需要为任意数量的键工作,而不仅仅是1和2,但即使有10个左右。 1和2是学生,' hw' qz'等等是作业的类别,每个学生将有hw,qz,ex,pr,并且将有每个学生3 qz,3hw,3pr,3ex。我需要归还所有学生1级,hw级,1级测验级,2级hw级等等。

grades = {
        1: {
            'pr': [18, 15],
            'hw': [16, 27, 25], 
            'qz': [8, 10, 5],
            'ex': [83, 93],
            },
        2: {
            'pr': [20, 18],
            'hw': [17, 23, 28],
            'qz': [9, 9, 8],
            'ex': [84, 98],
            },
        }

2 个答案:

答案 0 :(得分:2)

更简洁(和Pythonicly):

hw_sum = sum([grades[key]['hw'][0] for key in grades])

答案 1 :(得分:0)

  

返回键内的第一个值' hw'对于键1和键2并加以总结

它有助于使用解释性名称,因此我们知道移动部件的意图。我通过猜测其含义,选择了一些描述性的名字。

简洁解决方案

grades_by_year_and_subject = {
        1: {
            'pr': [18, 15],
            'hw': [16, 27, 25], 
            'qz': [8, 10, 5],
            'ex': [83, 93],
            },
        2: {
            'pr': [20, 18],
            'hw': [17, 23, 28],
            'qz': [9, 9, 8],
            'ex': [84, 98],
            },
        }

sum_of_grades_for_year_1_and_2_for_subject_hw = sum(
        grades[0] for grades in (
            grades_by_subject['hw']
            for (year, grades_by_subject) in
                grades_by_year_and_subject.items()
            if year in [1, 2]
            )
        )

将其分解为几个较小的问题:

对值集合

求和
sum_of_grades = sum(values)

从列表集合中获取第一个值的集合

set_of_first_grades = {
        values[0] for values in collection}

从集合

为每个dict中的键'hw'生成值
generator_of_hw_value_lists = (
        values_dict['hw'] for values_dict in
        collection_of_dicts.values())

仅将字典缩减为具有键12

的项目
mapping_of_values_for_key_1_and_2 = {
        key: value
        for (key, value) in values_dict.items()
        if key in [1, 2]}

详细解决方案

grades_by_year_and_subject = {
        1: {
            'pr': [18, 15],
            'hw': [16, 27, 25], 
            'qz': [8, 10, 5],
            'ex': [83, 93],
            },
        2: {
            'pr': [20, 18],
            'hw': [17, 23, 28],
            'qz': [9, 9, 8],
            'ex': [84, 98],
            },
        }

grades_for_year_1_and_2_by_subject = {
        year: grades_by_subject
        for (year, grades_by_subject) in
            grades_by_year_and_subject.items()
        if year in [1, 2]}

grades_for_year_1_and_2_for_subject_hw = (
        grades_by_subject['hw']
        for grades_by_subject in
            grades_for_year_1_and_2_by_subject.values())

sum_of_grades_for_year_1_and_2_for_subject_hw = sum(
        grades[0] for grades in grades_for_year_1_and_2_for_subject_hw)
相关问题