аватар question@mail.ru · 01.01.1970 03:00

Get the last key in the python dictionary

There is a dictionary:

  Dicid = { 1 : [ 3 ,  4 ],  2 : [ 5 ,  6 ,  3 ],  3 : [ 7 ,  1 ,  9 ,  2 ]}     

you need to get the last key in this dictionary.

  Dicid.keys () // Retus the set Klyuche    

how to choose the latter from them?

аватар answer@mail.ru · 01.01.1970 03:00

To get the last element from an arbitrary collection:

   & gt; & gt; & gt;  d = { 'a' :  1 ,  'b' :  & gt; & gt; & gt;   Import  collections  & gt; & gt; & gt;  [Last] = collections.deque (D, maxlen =  1 )   & gt; & gt; & gt;  Last  'b'      

this o (n) in time, o (1) in memory the algorithm. For comparison: list (d) [-1] requires O (n) memory.

to Pytho 3.7, the keys in the dictionary are not ordered, so the concept of "last" "" "" dict :

   & gt; & gt;   from  collections  Import  orDereddict  & gt; & gt; & gt;  d = orDereddict (a =  1 , b =  2 ) # python 3.6 kwargs Order    & gt; & gt; & gt;  Last =  next  ( reversed  (d))   & gt; & gt; & gt;  Last  'b'      

this is the optimal O (1) time and memory algorithm. Perhaps in the future this code will also work for the built -in DICT:

Latest

Similar