如何只添加键s1中的值

时间:2019-02-22 07:01:39

标签: python dictionary

students={
1: {"pup1": "001", "s1": 10, "s2": 20},

2: {"pup2": "124", "s1": 20, "s2": 30},

3: {"pup3": "125", "s1": 30, "s2": 40}}
  1. 列表项

1 个答案:

答案 0 :(得分:-2)

如果要添加s1的所有值,则需要遍历字典学生的values()

    students={
1: {"pup1": "001", "s1": 10, "s2": 20},

2: {"pup2": "124", "s1": 20, "s2": 30},

3: {"pup3": "125", "s1": 30, "s2": 40}}

sum1 = 0
for data in students.values():
    sum1 += data['s1']

avg = sum1 / len(students)

print(sum1)
print(avg)