Last Key in Python Dictionary

后端 未结 10 846
栀梦
栀梦 2021-01-31 13:58

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 13:59

    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.

    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).

    0 讨论(0)
  • 2021-01-31 13:59

    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.

    mydict = {'John':'apple','Mat':'orange','Jane':'guava','Kim':'apple','Kate': 'grapes'}
    
    mydict.keys()
    

    output: dict_keys(['John', 'Mat', 'Jane', 'Kim', 'Kate'])

    list(mydict.keys())
    

    output: ['John', 'Mat', 'Jane', 'Kim', 'Kate']

    list(mydict.keys())[-1]
    

    output: 'Kate'

    0 讨论(0)
  • 2021-01-31 14:00

    Since python 3.7 dict always ordered(insert order),

    since python 3.8 keys(), values() and items() of dict returns: view that can be reversed:

    to get last key:

    next(reversed(my_dict.keys()))  
    

    the same apply for values() and items()

    PS, to get first key use: next(iter(my_dict.keys()))

    0 讨论(0)
  • 2021-01-31 14:07

    In python 3.6 I got the value of last key from the following code

    list(dict.keys())[-1]
    
    0 讨论(0)
  • 2021-01-31 14:09

    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).

    0 讨论(0)
  • 2021-01-31 14:10

    yes there is : len(data)-1.

    For the first element it´s : 0

    0 讨论(0)
提交回复
热议问题