Python 字典中的最后一个键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16125229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Last Key in Python Dictionary
提问by cbbcbail
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:
我很难弄清楚 Python 字典中最后一个键的语法是什么。我知道对于 Python 列表,人们可能会说这表示最后一个:
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 doesnt work:
但是,当我尝试使用以下逻辑代码时,它不起作用:
dict.keys(-1)
It says that keys cant take any arguments and 1 is given. If keys cant take args, then how can I denote that I want the last key in the list?
它说键不能接受任何参数,并且给出了 1。如果键不能带参数,那么我如何表示我想要列表中的最后一个键?
XXXXX 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.XXXXX
XXXXX 我的操作假设 Python 字典按照项目添加到字典的顺序排序,最近的项目最后。出于这个原因,我想访问字典中的最后一个键。XXXXX
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?
我现在被告知字典键不是按添加时间排序的。那么我如何才能选择最近添加的密钥?
采纳答案by root
If insertion order matters, take a look at collections.OrderedDict:
如果插入顺序很重要,请查看collections.OrderedDict:
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.
OrderedDict 是一个 dict,它记住第一次插入键的顺序。如果新条目覆盖现有条目,则原始插入位置保持不变。删除一个条目并重新插入它会将它移到最后。
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')
回答by aldeb
It seems like you want to do that:
看起来你想这样做:
dict.keys()[-1]
dict.keys()returns a list of your dictionary's keys. Once you got the list, the -1 index allows you getting the last element of a list.
dict.keys()返回字典键的列表。获得列表后,-1 索引允许您获取列表的最后一个元素。
Since a dictionary is unordered, it's doesn't make sense to get the last key of your dictionary.
由于字典是无序的,因此获取字典的最后一个键是没有意义的。
Perhaps you want to sort them before. It would look like that:
也许您想先对它们进行排序。它看起来像这样:
sorted(dict.keys())[-1]
Note:
笔记:
In Python 3, the code is
在 Python 3 中,代码是
list(dict)[-1]
回答by Daniel Roseman
It doesn't make sense to ask for the "last" key in a dictionary, because dictionary keys are unordered. You can get the list of keys and get the last one if you like, but that's not in any sense the "last key in a dictionary".
要求字典中的“最后一个”键没有意义,因为字典键是无序的。如果您愿意,您可以获取键列表并获取最后一个,但这在任何意义上都不是“字典中的最后一个键”。
回答by 0x90
sorted(dict.keys())[-1]
Otherwise, the keysis just an unordered list, and the "last one" is meaningless, and even can be different on various python versions.
否则,这keys只是一个无序列表,“最后一个”是没有意义的,甚至在不同的python版本上都可能不同。
Maybe you want to look into OrderedDict.
也许你想看看OrderedDict。
回答by Eric Cross
There are absolutely very good reason to want the last key of an OrderedDict. I use an ordered dict to list my users when I edit them. I am using AJAX calls to update user permissions and to add new users. Since the AJAX fires when a permission is checked, I want my new user to stay in the same position in the displayed list (last) for convenience until I reload the page. Each time the script runs, it re-orders the user dictionary.
绝对有很好的理由需要 OrderedDict 的最后一个键。我在编辑用户时使用有序的 dict 来列出我的用户。我正在使用 AJAX 调用来更新用户权限并添加新用户。由于在检查权限时会触发 AJAX,为了方便起见,我希望我的新用户保持在显示列表(最后一个)中的相同位置,直到我重新加载页面。每次脚本运行时,它都会重新排序用户字典。
That's all good, why need the last entry? So that when I'm writing unit tests for my software, I would like to confirm that the user remains in the last position until the page is reloaded.
一切都很好,为什么需要最后一个条目?因此,当我为我的软件编写单元测试时,我想确认用户保持在最后一个位置,直到页面重新加载。
dict.keys()[-1]
Performs this function perfectly (Python 2.7).
完美地执行此功能(Python 2.7)。
回答by Victor
yes there is : len(data)-1.
是的,有:len(data)-1。
For the first element it′s : 0
对于第一个元素,它是:0
回答by Matheus
You can do a function like this:
你可以做一个这样的功能:
def getLastItem(dictionary):
last_keyval = dictionary.popitem()
dictionary.update({last_keyval[0]:last_keyval[1]})
return {last_keyval[0]:last_keyval[1]}
This not change the original dictionary! This happen because the popitem() function returns a tuple and we can utilize this for us favor!!
这不是改变原来的字典!发生这种情况是因为 popitem() 函数返回一个元组,我们可以利用它来帮助我们!!
回答by rahul4data
There's a definite need to get the last element of a dictionary, for example to confirm whether the latest element has been appended to the dictionary object or not.
确实需要获取字典的最后一个元素,例如确认最新的元素是否已附加到字典对象中。
We need to convert the dictionary keys to a list object, and use an index of -1 to print out the last element.
我们需要将字典键转换为列表对象,并使用 -1 的索引打印出最后一个元素。
mydict = {'John':'apple','Mat':'orange','Jane':'guava','Kim':'apple','Kate': 'grapes'}
mydict.keys()
output: dict_keys(['John', 'Mat', 'Jane', 'Kim', 'Kate'])
输出:dict_keys(['John', 'Mat', 'Jane', 'Kim', 'Kate'])
list(mydict.keys())
output: ['John', 'Mat', 'Jane', 'Kim', 'Kate']
输出:['John', 'Mat', 'Jane', 'Kim', 'Kate']
list(mydict.keys())[-1]
output: 'Kate'
输出:'凯特'
回答by ravichandra vydhya
In python 3.6 I got the value of last key from the following code
在python 3.6中,我从以下代码中获得了最后一个键的值
list(dict.keys())[-1]

