Home > front end >  Retrieving Last value of a python dictionary
Retrieving Last value of a python dictionary

Time:04-05

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

CodePudding user response:

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)

CodePudding user response:

Python docs (v3.7 ) say:

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.

Therefore list(d)[-1] results in final key, d[list(d)[-1]] will return final value.

Prior to python 3.7, dictionaries were unordered.

CodePudding user response:

If your code relies on the last value you might have a design problem. While dicts are insertion-ordered in 3.7, their primary purpose is to map keys to values.

That being said, you can use

last = next(reversed(d.values()))

Note that next can take an optional fallback value in case your dictionary could be empty.

CodePudding user response:

For the last value you can use the code print(list(d.values())[-1]) to turn the dictionary into a list of values, and then just get the last one with [-1].

  • Related