Last Key in Python Dictionary

后端 未结 10 875
栀梦
栀梦 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'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'

提交回复
热议问题