Python 字典中的最后一个键 [英] Last Key in Python Dictionary

查看:182
本文介绍了Python 字典中的最后一个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚 Python 字典中最后一个键的语法是什么.我知道对于 Python 列表,人们可能会说这表示最后一个:

I am having difficulty figuring out what the syntax would be for the last key in a Python dictionary. I know that for a Python list, one may say this to denote the last:

list[-1]

我也知道可以按如下方式获取字典的键列表:

I also know that one can get a list of the keys of a dictionary as follows:

dict.keys()

但是,当我尝试使用以下逻辑代码时,它不起作用:

However, when I attempt to use the logical following code, it doesn't work:

dict.keys(-1)

它说键不能带任何参数,并且给出了 1.如果键不能带参数,那么我如何表示我想要列表中的最后一个键?

It says that keys can't take any arguments and 1 is given. If keys can't take arguments, then how can I denote that I want the last key in the list?

我的操作假设 Python 词典按项目添加到词典的顺序排序,最近的项目最后.因此,我想访问字典中的最后一个键.

I am operating under the assumption that Python dictionaries are ordered in the order in which items are added to the dictionary with most recent item last. For this reason, I would like to access the last key in the dictionary.

我现在被告知字典键不是按添加时间排序的.那么我如何才能选择最近添加的密钥?

I am now told that the dictionary keys are not in order based on when they were added. How then would I be able to choose the most recently added key?

推荐答案

如果插入顺序很重要,请查看 collections.OrderedDict:

If insertion order matters, take a look at collections.OrderedDict:

OrderedDict 是一个 dict,它记住第一次插入键的顺序.如果新条目覆盖现有条目,则原始插入位置保持不变.删除条目并重新插入会将其移至末尾.

An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.


In [1]: from collections import OrderedDict

In [2]: od = OrderedDict(zip('bar','foo'))

In [3]: od
Out[3]: OrderedDict([('b', 'f'), ('a', 'o'), ('r', 'o')])

In [4]: od.keys()[-1]
Out[4]: 'r'

In [5]: od.popitem() # also removes the last item
Out[5]: ('r', 'o')

更新:

不再需要 OrderedDict,因为从 Python 3.7 开始(在 3.6 中非正式地)字典键按插入顺序正式排序.

Update:

An OrderedDict is no longer necessary as dictionary keys are officially ordered in insertion order as of Python 3.7 (unofficially in 3.6).

对于这些最新的 Python 版本,您可以改为使用 list(my_dict)[-1]list(my_dict.keys())[-1].

For these recent Python versions, you can instead just use list(my_dict)[-1] or list(my_dict.keys())[-1].

这篇关于Python 字典中的最后一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆