Search code examples
pythondictionaryordereddictionary

How do you find the first item in a dictionary?


I am trying to get the first item I inserted in my dictionary (which hasn't been re-ordered). For instance:

_dict = {'a':1, 'b':2, 'c':3}

I would like to get the tuple ('a',1)

How can I do that?


Solution

  • Before Python 3.6, dictionaries were un-ordered, therefore "first" was not well defined. If you wanted to keep the insertion order, you would have to use an OrderedDict: https://docs.python.org/2/library/collections.html#collections.OrderedDict

    Starting from Python 3.6, the dictionaries keep the insertion order by default ( see How to keep keys/values in same order as declared? )

    Knowing this, you just need to do

    first_element = next(iter(_dict.items()))
    

    Note that since _dict.items() is not an iterator but is iterable, you need to make an iterator for it by calling iter.

    The same can be done with keys and values:

    first_key = next(iter(_dict))
    first_value = next(iter(_dict.values()))