Reputation: 323
I need to create a function named stats to return a list of lists where the first item in each inner list is the teacher's name and the second item in the number of courses that teacher has. It should return: [["Tom Smith", 6], ["Emma Li", 3]]
Argument is a dictionary that looks like:
teacher_dict = {'Tom Smith': ['a', 'b', 'c', 'd', 'e', 'f'], 'Emma Li': ['x', 'y', 'z']}
Here is my attempt:
def stats(teacher_dict):
big_list = []
for teacher, courses in teacher_dict.items():
number_of_courses = []
for key in teacher_dict:
teacher = ''
num = 0
for item in teacher_dict[key]:
num += 1
number_of_courses.append((key,num))
return big_list.append([teacher, number_of_courses])
Another attempt:
def stats(teacher_dict):
big_list = []
for teacher in teacher_dict.items():
number_of_courses = len(teacher_dict[teacher])
return big_list.append([teacher, number_of_courses])
Any help is greatly appreciated! Both scripts have errors, and I am still very junior in Python, but really want to figure this out. Thank you.
Upvotes: 0
Views: 56
Reputation: 223122
Your code example is almost good to go, problem is that the return
statement ends the function prematurely. Also the append
call must be inside the loop:
def stats(teacher_dict):
big_list = []
for teacher in teacher_dict.items():
number_of_courses = len(teacher_dict[teacher])
big_list.append([teacher, number_of_courses])
return big_list
Upvotes: 0
Reputation: 36
teacher_dict = {'Tom Smith': ['a', 'b', 'c', 'd', 'e', 'f'], 'Emma Li': ['x', 'y', 'z']}
stats = lambda teacher_dict: [[teacher, len(courses)] for teacher, courses in teacher_dict.items()]
stats(teacher_dict)
Outputs: [['Emma Li', 3], ['Tom Smith', 6]]
Upvotes: 0
Reputation: 61052
Use a list comprehension
[[k, len(v)] for k, v in teacher_dict.items()]
Upvotes: 2