Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find the first item in a dictionary? [duplicate]

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?

like image 491
Dominus Avatar asked Oct 20 '25 03:10

Dominus


1 Answers

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()))
like image 175
Dominus Avatar answered Oct 21 '25 16:10

Dominus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!