1

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?

Dominus
  • 808
  • 11
  • 25
  • 1
    This has already been asked [here](https://stackoverflow.com/questions/30362391/how-do-you-find-the-first-key-in-a-dictionary) – yatu Apr 15 '20 at 09:51
  • @yatu indeed, in fact I mentioned it in my own answer. However they do not make the distinction between python 2, 3, and >=3.6, hence this was my contribution after getting confused at that answer you mentioned, and looking around a bit more – Dominus Apr 15 '20 at 09:58
  • The first don't, but it looks like it is covered in the third answer https://stackoverflow.com/a/30362701/9698684 – yatu Apr 15 '20 at 10:02

1 Answers1

4

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()))
user2357112
  • 260,549
  • 28
  • 431
  • 505
Dominus
  • 808
  • 11
  • 25
  • What are you trying to do here? By posting a question and answer to it yourself at same time? – MohitC Apr 15 '20 at 09:51
  • 2
    @MayankPorwal see [Can I answer my own question?](https://stackoverflow.com/help/self-answer) – yatu Apr 15 '20 at 09:53
  • Yes, it's a Q&A (Just try "asking a question" and you'll see Stackoverflow gives you the possibility to do that). I did that because you you type that question on google, the first result is outdated: https://stackoverflow.com/questions/30362391/how-do-you-find-the-first-key-in-a-dictionary – Dominus Apr 15 '20 at 09:53
  • This is quite common here in SO actually, and also encouraged. It is also mentioned in the link I've mentioned @MayankPorwal – yatu Apr 15 '20 at 09:56
  • My Bad. Agreed. – Mayank Porwal Apr 15 '20 at 09:58