3 回答
TA贡献2065条经验 获得超14个赞
如果您只需要使用 for 循环而不使用方法,那么您可以这样做:
new_dict = {}
for subject,students in classGrades.items():
for names, marks in students.items():
if names in new_dict:
new_dict[names].update({subject:marks})
else:
new_dict[names] = {subject:marks}
print(new_dict)
输出:
{'Bob': {'Computer Science': [98, 100, 100, 88], 'Chemistry': [98, 100, 100, 88]}, 'Sue': {'Computer Science': [100, 88, 100, 100], 'English': [100, 100, 100, 100, 88], 'Chemistry': [88, 88, 88, 88]}, 'Jill': {'Computer Science': [100, 100, 100, 100], 'Chemistry': [100, 100, 100, 100]}, 'Mary': {'English': [88, 90, 88, 90, 88]}, 'John': {'English': [100, 100, 100, 100, 100]}, 'Joe': {'English': [90, 90, 70, 70, 80]}}
TA贡献1898条经验 获得超8个赞
你可以这样做:
classGrades = {
"Computer Science": {"Bob": [98, 100, 100, 88], "Sue": [100, 88, 100, 100], "Jill": [100, 100, 100, 100]},
"English": {"Sue": [100, 100, 100, 100, 88], "Mary": [88, 90, 88, 90, 88], "John": [100, 100, 100, 100, 100],
"Joe": [90, 90, 70, 70, 80]},
"Chemistry": {"Bob": [98, 100, 100, 88], "Sue": [88, 88, 88, 88], "Jill": [100, 100, 100, 100]}}
result = {}
for _class, names in classGrades.items():
for name, grade in names.items():
result.setdefault(name, {})[_class] = grade
print(result)
输出
{'Mary': {'English': [88, 90, 88, 90, 88]}, 'Joe': {'English': [90, 90, 70, 70, 80]}, 'Sue': {'Computer Science': [100, 88, 100, 100], 'English': [100, 100, 100, 100, 88], 'Chemistry': [88, 88, 88, 88]}, 'Jill': {'Computer Science': [100, 100, 100, 100], 'Chemistry': [100, 100, 100, 100]}, 'Bob': {'Computer Science': [98, 100, 100, 88], 'Chemistry': [98, 100, 100, 88]}, 'John': {'English': [100, 100, 100, 100, 100]}}
TA贡献2041条经验 获得超4个赞
您可以使用collections.defaultdict. 由于defaultdict是 的子类,dict因此通常无需转换回常规dict.
from collections import defaultdict
dd = defaultdict(lambda: defaultdict(list))
for subject, names in classGrades.items():
for name, grades in names.items():
dd[name][subject] = grades
结果:
print(dd)
defaultdict(<function __main__.<lambda>>,
{'Bob': defaultdict(list,
{'Chemistry': [98, 100, 100, 88],
'Computer Science': [98, 100, 100, 88]}),
'Jill': defaultdict(list,
{'Chemistry': [100, 100, 100, 100],
'Computer Science': [100, 100, 100, 100]}),
'Joe': defaultdict(list, {'English': [90, 90, 70, 70, 80]}),
'John': defaultdict(list, {'English': [100, 100, 100, 100, 100]}),
'Mary': defaultdict(list, {'English': [88, 90, 88, 90, 88]}),
'Sue': defaultdict(list,
{'Chemistry': [88, 88, 88, 88],
'Computer Science': [100, 88, 100, 100],
'English': [100, 100, 100, 100, 88]})})
添加回答
举报