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 Dictionary Iteration

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,809 Points

Is 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
Steven Parker
231,269 Points

Dictionaries 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]

I 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
Steven Parker
231,269 Points

By itself, "dict.keys()" returns an iterable object but it is not a list and does not support indexing.

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,809 Points

In 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