且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 字典中的最后一个键

更新时间:2023-11-10 08:09:10

如果插入顺序很重要,请查看 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].