Explain Codes LogoExplain Codes Logo

How do you find the first key in a dictionary?

python
functions
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 13, 2024
TLDR

Don't keep the program waiting! Quickly fetch the first key from a Python 3.7+ dictionary:

first_key = next(iter(my_dict), 'Default')

This neat trick gets the job done and also takes care of possible StopIteration exceptions by supplying a default value if the dictionary decides to go on a vacation (aka, it's empty). Notice, this method only works if the keys have organized themselves in order - which they began doing so only from Python 3.7 onwards.

Getting the first key in older Python versions

If you're taking a trip down memory lane with Python 3.6 or older, step right this way:

from collections import OrderedDict old_school_dict = OrderedDict([('apple', 1), ('banana', 2)]) # Old-school vibe first_key = next(iter(old_school_dict)) # The apple falls first

Back in the day, dictionaries didn't care about the order of keys, which is why we've used collections.OrderedDict for our nostalgic journey.

A well-ordered list

Here's another technique if those keys could line up nicely to get snapped (into a list):

first_key = list(my_dict.keys())[0] if my_dict else 'Default' # Line 'em up, count 'em off

It's good to keep in mind that this method can be expensive for large dictionaries since queuing up keys like this creates a new list.

Unpack 'em

Here's a special treat trick using key unpacking:

first_key, *lazy_keys = my_dict.keys() # We've got a volunteer for the key disappearing act!

This trick gets the first key in the audience and relegates the rest to bystanders. Beware though, *lazy_keys can get inefficient when the audience (dictionary) grows large.

Good ol' loop

If you are old school and like to iterate explicitly:

for first_key in my_dict: print(f"The first key is {first_key}, bet you didn't see that coming!") break # Stop the key interrogation after the first one

No tricks, just simple old loop magic.

Timing is everything

If you're a stickler for efficiency and performance:

import cProfile cProfile.run('next(iter(my_dict))') # Find out how long the key's bathroom break took

Profiling each method will help you pick the perfect key for the lock.

Direct approach

Sometimes, you just have to ask for what you want, directly:

print(my_dict['banana']) # Make sure 'banana' isn't playing hide and seek

This approach will print the value of the specific key if it exists. Beware, 'banana' can be elusive, triggering a KeyError.