How do you find the first key in a dictionary?

slagoy picture slagoy · May 21, 2015 · Viewed 377.7k times · Source

I am trying to get my program to print out "banana" from the dictionary. What would be the simplest way to do this?

This is my dictionary:

prices = {
    "banana" : 4,
    "apple" : 2,
    "orange" : 1.5,
    "pear" : 3
}

Answer

maxbellec picture maxbellec · Sep 2, 2016

On a Python version where dicts actually are ordered, you can do

my_dict = {'foo': 'bar', 'spam': 'eggs'}
next(iter(my_dict)) # outputs 'foo'

For dicts to be ordered, you need Python 3.7+, or 3.6+ if you're okay with relying on the technically-an-implementation-detail ordered nature of dicts on Python 3.6.

For earlier Python versions, there is no "first key".