Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving Last value of a python dictionary

d={'Bat':1,'Tennisball':3,'Racquet':2,'Shuttlecock':3,'Javelin':1,'Soccer':1,'Hockey':7,'Gloves':8}

I want the last value of dictionary not key

like image 494
Sahil Avatar asked Oct 24 '25 13:10

Sahil


1 Answers

The most efficient way, in O(1), is to use dict.popitem:

k, last_value = _, d[k] = d.popitem()

LIFO order is guaranteed since Python 3.7 (the same version when dictionary insertion ordering was guaranteed).

If the double assignment seems too tricky, consider

last_value = d[next(reversed(d))]

Here are the timing comparisons (CPython 3.10 on linux):

>>> d={'Bat':1,'Tennisball':3,'Racquet':2,'Shuttlecock':3,'Javelin':1,'Soccer':1,'Hockey':7,'Gloves':8}
>>> timeit k, last_value = _, d[k] = d.popitem()
107 ns ± 3.34 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> timeit next(reversed(d.values()))
150 ns ± 0.237 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> timeit d[next(reversed(d))]
134 ns ± 0.503 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
like image 177
wim Avatar answered Oct 27 '25 01:10

wim



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!