[英]Changing nested dictionary values in python
I have a dictionary, who's keys are student ID #'s and the values are another dictionary. 我有一本字典,谁的钥匙是学生ID#,而值是另一本字典。 The nested dictionary has keys that state the type of assignment, and the values are the grades for the assignment, in a list. 嵌套字典在列表中具有说明作业类型的键,值是作业的等级。
So I'm trying to change the list of grades for each assignment (to drop lowest grade, average them, etc.), but I can't figure out a way to pick them out of the dictionary in the first place. 因此,我正在尝试更改每个作业的成绩列表(以降低最低成绩,取平均值,等等),但我想不出一种方法将它们从字典中挑选出来。
Here's what part of the dictionary looks like: 这是字典部分的内容:
D = {"123-45-6789":{"hw":[98,89,92,75], "quiz":[45,36,42,50,29,27,40,41], "exam":[175,157]}, "534-77-9326":{"hw":[67,89,55,78], "quiz":[78,45,67,23,45,78,88,91], "exam":[187,146]}, ....... etc.
Any help will be very appreciated. 任何帮助将不胜感激。
***and I forgot to mention that I planned on iterating through the dictionary to edit each list of grades, because there are many student ID #'s. ***,我忘了提到我计划遍历字典以编辑每个年级列表,因为有很多学生证号。 So I guess what I'm really asking is: What would the syntax look like to refer to each student ID #, then each list of grades for every ID # 所以我想我真正要问的是:语法是指每个学生ID#,然后是每个 ID#的每个成绩列表的语法?
You can get the list in the dictionary using assignment expression: 您可以使用赋值表达式在字典中获取列表:
lst = students_grades_dictionary["123-45-6789"]["hw"]
You can remove a grade from the list by using the pop function: 您可以使用弹出功能从列表中删除成绩:
lst.pop(<grade index>)
Since lst
is a reference to the grade list, any changes you made to it will also change the grade list in the dictionary. 由于lst
是对成绩列表的引用,因此您对其所做的任何更改也会更改词典中的成绩列表。
You can use a mixture of list.remove
and min()
after finding the length of the list. 找到列表的长度后,可以混合使用list.remove
和min()
。
max_size = 4
new_score = 87
hw_list = data[student_id]['hw']
if len(hw_list) >= max_size - 1:
hw_list.remove(min(hw_list))
hw_list.append(new_score)
Note this will not handle if the list is already more than 2 items larger than the specified max len
but this will get you started. 请注意,如果列表已经比指定的最大len
大2个以上,则此方法将无法处理,但这将使您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.