Last Key in Python Dictionary

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

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

提交回复
热议问题