Last Key in Python Dictionary

后端 未结 10 1952
轻奢々
轻奢々 2021-01-31 13:32

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:

10条回答
  •  盖世英雄少女心
    2021-01-31 14:19

    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.

    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

    list(dict)[-1]
    

    *Update:

    This is no longer the case. Dictionary keys are officially ordered as of Python 3.7 (and unofficially in 3.6).

提交回复
热议问题