How do you find the first key in a dictionary?

PythonDictionary

Python Problem Overview


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
}
    

Python Solutions


Solution 1 - Python

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", but this will give you "a key", especially useful if there is only one.

Solution 2 - Python

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]

Solution 3 - Python

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.

source


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 collections
prices  = 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

keys = list(prices)
print(keys[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.

Solution 4 - Python

If you just want the first key from a dictionary you should use what many have suggested before

first = next(iter(prices))

However if you want the first and keep the rest as a list you could use the values unpacking operator

first, *rest = prices

The same is applicable on values by replacing prices with prices.values() and for both key and value you can even use unpacking assignment

>>> (product, price), *rest = prices.items()
>>> product
'banana'
>>> price
4

> Note: You might be tempted to use first, *_ = prices to just get the first key, but I would generally advice against this usage unless the dictionary is very short since it loops over all keys and creating a list for the rest has some overhead.

> Note: As mentioned by others insertion order is preserved from python 3.7 (or technically 3.6) and above whereas earlier implementations should be regarded as undefined order.

Solution 5 - Python

The dict type is an unordered mapping, so there is no such thing as a "first" element.

What you want is probably collections.OrderedDict.

Solution 6 - Python

So I found this page while trying to optimize a thing for taking the only key in a dictionary of known length 1 and returning only the key. The below process was the fastest for all dictionaries I tried up to size 700.

I tried 7 different approaches, and found that this one was the best, on my 2014 Macbook with Python 3.6:

def first_5():
    for key in biased_dict:
        return key

The results of profiling them were:

  2226460 / s with first_1
  1905620 / s with first_2
  1994654 / s with first_3
  1777946 / s with first_4
  3681252 / s with first_5
  2829067 / s with first_6
  2600622 / s with first_7

All the approaches I tried are here:

def first_1():
    return next(iter(biased_dict))


def first_2():
    return list(biased_dict)[0]


def first_3():
    return next(iter(biased_dict.keys()))


def first_4():
    return list(biased_dict.keys())[0]


def first_5():
    for key in biased_dict:
        return key


def first_6():
    for key in biased_dict.keys():
        return key


def first_7():
    for key, v in biased_dict.items():
        return key

Solution 7 - Python

Well as simple, the answer according to me will be

first = list(prices)[0]

converting the dictionary to list will output the keys and we will select the first key from the list.

Solution 8 - Python

As many others have pointed out there is no first value in a dictionary. The sorting in them is arbitrary and you can't count on the sorting being the same every time you access the dictionary. However if you wanted to print the keys there a couple of ways to it:

for key, value in prices.items():
    print(key)

This method uses tuple assignment to access the key and the value. This handy if you need to access both the key and the value for some reason.

for key in prices.keys():
    print(key)

This will only gives access to the keys as the keys() method implies.

Solution 9 - Python

Use a for loop that ranges through all keys in prices:

for key, value in prices.items():
     print key
     print "price: %s" %value

Make sure that you change prices.items() to prices.iteritems() if you're using Python 2.x

Solution 10 - Python

d.keys()[0] to get the individual key.

Update:- @AlejoBernardin , am not sure why you said it didn't work. here I checked and it worked. import collections

prices  = collections.OrderedDict((

    ("banana", 4),
    ("apple", 2),
    ("orange", 1.5),
    ("pear", 3),
))
prices.keys()[0]

>> 'banana'

Solution 11 - Python

Assuming you want to print the first key:

print(list(prices.keys())[0])

If you want to print first key's value:

print(prices[list(prices.keys())[0]])

Solution 12 - Python

Use the one liner below which is quite logical and fast. On a for loop just call break imediatelly to exit and have the values.

for first_key in prices:  break
print(first_key)

If you also want the key and the value.

for first_key, first_value in prices.items():  break
print(first_key, first_value)

Solution 13 - Python

This will work in Python 2 but won't work in Python 3 (TypeError: 'dict_keys' object is not subscriptable):

first_key = my_dict.keys()[0]  

For a small list, if e.g. you get a response as a dict and it is one element you can convert it to list first:

assert len(my_dict)==1
key = list(my_dict.keys())[0]

If its a rather long dict, better use the method sujested by @Ryan as it should be more efficient.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionslagoyView Question on Stackoverflow
Solution 1 - PythonmaxbellecView Answer on Stackoverflow
Solution 2 - PythonylnorView Answer on Stackoverflow
Solution 3 - PythonRyan HainingView Answer on Stackoverflow
Solution 4 - PythonwihlkeView Answer on Stackoverflow
Solution 5 - Pythonuser1084944View Answer on Stackoverflow
Solution 6 - PythonturiyagView Answer on Stackoverflow
Solution 7 - PythonnarwanimonishView Answer on Stackoverflow
Solution 8 - PythonkylieCattView Answer on Stackoverflow
Solution 9 - PythonMark MView Answer on Stackoverflow
Solution 10 - PythonAmit SharmaView Answer on Stackoverflow
Solution 11 - PythonFerdView Answer on Stackoverflow
Solution 12 - PythonTincu Stefan LucianView Answer on Stackoverflow
Solution 13 - Pythonnasim seifiView Answer on Stackoverflow