Python Python Collections (2016, retired 2019) Dictionaries Dictionary Iteration

Stephen Cole
PRO
Stephen Cole
Pro Student 9,560 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
171,137 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]
Tilak Muruduru Divakar
Tilak Muruduru Divakar
3,303 Points

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
171,137 Points

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

Stephen Cole
PRO
Stephen Cole
Pro Student 9,560 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