Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Dictionaries Teacher Stats

tangtai chen
tangtai chen
4,844 Points

How do I create a new dictionary from undetermined values?

I know how to create a new dictionary but it won't work since with undetermined values. here is my example code:

def most_courses(sample_dict): max_val = 0 teacher = "" courses_list = {} for k in sample_dict.keys(): # print(len(sample_dict[k])) if max_val < len(sample_dict[k]): max_val = len(sample_dict[k]) teacher = k courses_list = sample_dict[k] # print(max_val) print(teacher) print(courses_list)

I would like to create a dictionary with my keys being teacher, and my values being course_list, but since they are undetermined before the loop finishes, so how do I do this? are we able to do that with python? since it is a from a python challenge i might took the wrong approach.

1 Answer

In Order to add a new element to the dictionary update -> add element to dictionary append -> add element to list

x ={} # Create Dictionary
x.update({'Mr John': [ ]}) # Add Element with key (teacher name) and value an empty array

#Lookup the teacher's name and get the empty array then add the course one by one to the array
x['Mr John'].append('Python 101')