subscripting Python 3 dicts/getting the only value in a Python 3 dict

Emanuel Barry vgr255 at live.ca
Tue Jan 12 12:00:06 EST 2016


> 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
The equivalent in Python 3 is `list(d.values())[0]`
> None of this feels like the "one, and preferably only one, obvious way to do it" we all strive for. Any other ideas?

If you feel like doing that, `for v in d.values(): pass` will set `v` to your value. But it's a bit cryptic, so you can probably resort to the list() alternative above :)
- Emanuel 		 	   		  


More information about the Python-list mailing list