Last Key in Python Dictionary

后端 未结 10 847
栀梦
栀梦 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 14:11

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

    0 讨论(0)
  • 2021-01-31 14:13
    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)
  • 2021-01-31 14:21

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

    If insertion order matters, take a look at 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.


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

    Update:

    An OrderedDict is no longer necessary as dictionary keys are officially ordered in insertion order as of Python 3.7 (unofficially in 3.6).

    For these recent Python versions, you can instead just use list(my_dict)[-1] or list(my_dict.keys())[-1].

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