Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Jussi Piitulainen Newsgroups: comp.lang.python Subject: Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict Date: Tue, 12 Jan 2016 19:47:22 +0200 Organization: A noiseless patient Spider Lines: 38 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="305c68510616a2e7ac08bcd2ff1598bd"; logging-data="25302"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX181ei0JuJmR/YvGufGBLU360xhlHwk0zEs=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:a9SsD1n24BcqbF93+mrJ+aKvrjM= sha1:f0E2puTA97e8RRfN/ue2YHBAGQw= Xref: csiph.com comp.lang.python:101563 Nick Mellor writes: > 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: If you are happy to give the sole value a name: >>> shoe = dict(it=math.pi) >>> [o] = shoe.values() >>> o 3.141592653589793 You might be able to use * to pass the sole value to a function: >>> print(*shoe.values()) 3.141592653589793 But the most readable thing might be to have a function that extracts the sole value by whatever means: >>> def sole(d): [o] = d.values() ; return o ... >>> sole(shoe) 3.141592653589793