Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict Date: Tue, 12 Jan 2016 18:32:50 +0100 Organization: None Lines: 49 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de PIU7liYBPYLBGHIAitmzwglfwbH8+QzlBfRlW3KilWlA== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'subject:Python': 0.05; 'preferably': 0.05; 'indexing': 0.07; 'subject:getting': 0.07; 'item,': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'typeerror:': 0.09; 'python': 0.10; 'nick': 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; 'wrote:': 0.16; '>>>': 0.20; 'all,': 0.20; '"",': 0.22; 'problem:': 0.22; '(most': 0.24; 'header:User-Agent:1': 0.26; 'header:X-Complaints-To:1': 0.26; "skip:' 10": 0.28; 'dictionary': 0.29; 'seemingly': 0.29; 'subject:/': 0.30; 'code': 0.30; "i'd": 0.31; 'traceback': 0.33; 'file': 0.34; 'item': 0.35; 'there': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'received:org': 0.37; 'one,': 0.37; 'end': 0.39; 'whatever': 0.39; 'does': 0.39; 'subject:the': 0.39; 'to:addr:python.org': 0.40; 'where': 0.40; 'received:de': 0.40; 'is.': 0.63; 'obvious': 0.76; 'it"': 0.84; 'subject:value': 0.84; 'write:': 0.91 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd8ad4.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:101559 Nick Mellor wrote: > Hi all, > > Seemingly simple problem: > > There is a case in my code where I know a dictionary has only one item in > it. I want to get the value of that item, whatever the key is. > > In Python2 I'd write: > >>>> d = {"Wilf's Cafe": 1} >>>> d.values()[0] > 1 > > and that'd be an end to it. > > In Python 3: > >>>> d = {"Wilf's Cafe": 1} >>>> d.values()[0] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'dict_values' object does not support indexing > "Wilf's Cafe" >>>> d[list(d)[0]] > 1 > >>>> for k in d: > ... value = d[k] > ... break > ... >>>> value > 1 > >>>> list(d.values())[0] > 1 > > None of this feels like the "one, and preferably only one, obvious way to > do it" we all strive for. Any other ideas? If there is exactly one item you can unpack: >>> d = {"Wilf's Cafe": 1} >>> k, = d.values() >>> k 1