#python#从字典中获取字典并根据条件生成新字典

假如有成绩表如下:

score = {"A": {"chinese": 100,"math": 90, "english": 80},
         "B": {"chinese": 31, "math": 71, "english": 91},
         "C": {"chinese": 88, "math": 46, "english": 100},
         "D": {"chinese": 60, "math": 99, "english": 71},
         "E": {"chinese": 56, "math": 80, "english": 61},
         "F": {"chinese": 45, "math": 57, "english": 45}}

请编写代码,分别统计出每个科目,不及格(分数小于60)人员的名字;期望最终输出结果如下:

{'chinese':["B","E","F"],"math": ["C","F"],"english":["F"]}

你题目的解答代码如下:

score = {"A": {"chinese": 100,"math": 90, "english": 80},
         "B": {"chinese": 31, "math": 71, "english": 91},
         "C": {"chinese": 88, "math": 46, "english": 100},
         "D": {"chinese": 60, "math": 99, "english": 71},
         "E": {"chinese": 56, "math": 80, "english": 61},
         "F": {"chinese": 45, "math": 57, "english": 45}}

dic = {'chinese':[],"math": [],"english":[]}
for m,c in score.items():
    for k,v in c.items():
        if v<60:
            dic[k].append(m)
print(dic)

img

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

img


score = {"A": {"chinese": 100,"math": 90, "english": 80},
         "B": {"chinese": 31, "math": 71, "english": 91},
         "C": {"chinese": 88, "math": 46, "english": 100},
         "D": {"chinese": 60, "math": 99, "english": 71},
         "E": {"chinese": 56, "math": 80, "english": 61},
         "F": {"chinese": 45, "math": 57, "english": 45}}
lista = []
listb = []
listc = []
for key, value in score.items():
    for a,b in value.items():
        if b< 60 and a == "chinese":
            lista.append(key)
        if b<60 and a == "math":
            listb.append(key)
        if b<60 and a == "english":
            listc.append(key)
dict_final = {"chinese":lista, "math":listb, "english":listc}
print(dict_final)

基本就是一个遍历字典值,只不过是循环嵌套了,然后几个if就解决了