[英]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我想要字典的最后一个值而不是键
The most efficient way, in O(1) , is to use dict.popitem
:在O(1)中,最有效的方法是使用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).自 Python 3.7 起保证后进先出顺序(保证字典插入顺序时的相同版本)。
If the double assignment seems too tricky, consider如果双重分配看起来太棘手,请考虑
last_value = d[next(reversed(d))]
Here are the timing comparisons (CPython 3.10 on linux):以下是时间比较(Linux 上的 CPython 3.10):
>>> 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)
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].对于最后一个值,您可以使用代码print(list(d.values())[-1])
将字典转换为值列表,然后使用 [-1] 获取最后一个值。
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.虽然字典在 3.7 中是插入顺序的,但它们的主要目的是将 map 个键值。
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.请注意, next
可以采用可选的回退值,以防您的字典可能为空。
Python docs (v3.7+) say: Python 文档 (v3.7+) 说:
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).在字典上执行 list(d) 会返回字典中使用的所有键的列表,按插入顺序排列(如果你想对其进行排序,只需使用 sorted(d) 代替)。 To check whether a single key is in the dictionary, use the in keyword.要检查单个键是否在字典中,请使用 in 关键字。
Therefore list(d)[-1]
results in final key , d[list(d)[-1]]
will return final value.因此list(d)[-1]
结果是最终的key , d[list(d)[-1]]
将返回最终值。
Prior to python 3.7, dictionaries were unordered.在 python 3.7 之前,字典是无序的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.