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 trialStephen Cole
Courses Plus Student 15,809 PointsIs it possible to extract the key from a dict that has only one key/value pair without looping over it?
In the challenge on the section on dictionaries, I wanted to use a dict to store the name of the teacher with the most classes. Getting the value was easy enough but, I couldn't get just the key. (The name of the teacher.)
Is it possible to get the first (or only) key in a dict without looping over it? (Even if it is random.)
2 Answers
Steven Parker
231,269 PointsDictionaries have no order.
So the concept of "first" doesn't make sense. But you can get just the keys from a dictionary with the .keys() method.
And while you could not predict which key you might get, you could get just one key by converting the keys into a list and applying an index:
list(dict.keys())[0]
Stephen Cole
Courses Plus Student 15,809 PointsIn the next chapter of the course, I figured out how to get my key and value out of a single dictionary using a Tuple. However, using Mr. Parker's solution works nicely.
In response to Dmitry:
def most_courses(teacher_dict):
count = 0
teacher_with_most_classes = ""
for teacher in teacher_dict:
if len(teacher_dict[teacher]) > count:
count = len(teacher_dict[teacher])
teacher_with_most_classes = teacher
return teacher_with_most_classes
Tilak Muruduru Divakar
6,459 PointsTilak Muruduru Divakar
6,459 PointsI believe dict.keys() itself returns a list. I might be wrong. If it's the only key in the dictionary, the list will have only one item.
Steven Parker
231,269 PointsSteven Parker
231,269 PointsBy itself, "dict.keys()" returns an iterable object but it is not a list and does not support indexing.