Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: Returning a result from 3 items in a list Date: Tue, 24 Nov 2015 11:32:51 +0100 Organization: None Lines: 48 Message-ID: References: <133829df-f57f-442f-9dbf-b22b22f656ae@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de R6QGwxXu2Z+ax0xBnFLjigks7L7TKzX2YsHhIzahAeDg== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.002 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'lookup': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; '*list*': 0.16; '12)': 0.16; 'pair,': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'unordered': 0.16; 'wrote:': 0.16; '>>>': 0.20; '(the': 0.22; 'item.': 0.22; 'header:User- Agent:1': 0.26; 'subject:list': 0.26; 'header:X-Complaints-To:1': 0.26; 'define': 0.27; '14,': 0.27; 'function': 0.28; 'values': 0.28; '13,': 0.29; 'dictionary': 0.29; 'way?': 0.29; 'list': 0.34; 'false': 0.35; 'i.e.': 0.35; 'item': 0.35; 'there': 0.36; 'to:addr :python-list': 0.36; 'subject:: ': 0.37; 'thanks': 0.37; 'received:org': 0.37; 'subject:from': 0.39; 'takes': 0.39; 'to:addr:python.org': 0.40; 'received:de': 0.40; 'skip:n 10': 0.62; 'rare': 0.66; 'results': 0.66 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd94ca.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.20+ Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:99308 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