Cai Gengyang wrote: > Here's a dictionary with 3 values : > > results = { > "gengyang": 14, > "ensheng": 13, > "jordan": 12 > } > > How do I define a function that takes the last of the 3 items in that list > and returns Jordan's results i.e. (12) ? > > Thanks a lot !
You can access the last item in a *list* with items[-1]: >>> results = [ ... ("gengyang", 14), ... ("ensheng", 13), ... ("jordan", 12) ... ] >>> results[-1] ('jordan', 12) A *dict* is unordered (the order is undefined, to be exact), so there is no "last" item. For the rare case when you need both order and fast lookup there's collections.OrderedDict: >>> results = collections.OrderedDict([ ... ("gengyang", 14), ... ("ensheng", 13), ... ("jordan", 12) ... ]) Get the last value non-destructively: >>> results[next(reversed(results))] # is there a less tedious way? 12 Get the last pair, removing it from the dictionary: >>> results.popitem(last=True) ('jordan', 12) >>> "jordan" in results False -- https://mail.python.org/mailman/listinfo/python-list