How do you find the first key in a dictionary?
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".
A dictionary is not indexed, but it is in some way, ordered. The following would give you the first existing key:
list(my_dict.keys())[0]
Update: as of Python 3.7, insertion order is maintained, so you don't need an OrderedDict
here. You can use the below approaches with a normal dict
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Python 3.6 and earlier*
If you are talking about a regular dict
, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your dict
you will likely not get "banana"
as the first thing you see.
If you need to keep things in order, then you have to use an OrderedDict
and not just a plain dictionary.
import collectionsprices = collections.OrderedDict([ ("banana", 4), ("apple", 2), ("orange", 1.5), ("pear", 3),])
If you then wanted to see all the keys in order you could do so by iterating through it
for k in prices: print(k)
You could, alternatively put all of the keys into a list and then work with that
ks = list(prices)print(ks[0]) # will print "banana"
A faster way to get the first element without creating a list would be to call next
on the iterator. This doesn't generalize nicely when trying to get the nth
element though
>>> next(iter(prices))'banana'
* CPython had guaranteed insertion order as an implementation detail in 3.6.