Last Key in Python Dictionary

后端 未结 10 1951
轻奢々
轻奢々 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:21

    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:23

    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 14:24

    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!!

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

    Otherwise, the keys is just an unordered list, and the "last one" is meaningless, and even can be different on various python versions.

    Maybe you want to look into OrderedDict.

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