How to get single value from dict with single entry?

Question:

I saw How to extract dictionary single key-value pair in variables suggesting:

d = {"a":1}
(k, v), = d.items()

But: I only care about the value. And I want to pass that value to a method; like:

foo(v)

So the question is: is there a simple command that works for both python2 and python3 that gives me that value directly, without the detour of the “tuple” assignment?

Or is there a way to make the tuple assignment work for my usecase of calling a method?

Asked By: GhostCat

||

Answers:

list(d.values())[0] will be evaluated to 1.
As pointed out in the comments, the cast to list is only needed in python3.

next(iter(d.values())) is another possibility (probably more memory efficient, as you do not need to create a list)

Both solution testes locally with python 3.6.0 and in TIO with python 2.

Answered By: B. Barbieri

If you know the key then you can simply do :

d["a"] 
output :
1

and if you don’t know the key:

for key in d.keys():
d[key]

#so basically you have to do :

for key in d.keys():
f00(d[key])
Answered By: user7635602

is there a simple command that works for both python2 and python3 that
gives me that value directly, without the detour of the “tuple”
assignment?

The solution using dict.copy()(to preserve the original dict) and dict.popitem() functions:

d = {"a":1}
foo(d.copy().popitem()[1])
Answered By: RomanPerekhrest

next(iter(d.values())) is the natural way to extract the only value from a dictionary. Conversion to list just to extract the only element is not necessary.

It is also performs best of the available options (tested on Python 3.6):

d = [{'a': i} for i in range(100000)]

%timeit [next(iter(i.values())) for i in d]  # 50.1 ms per loop
%timeit [list(i.values())[0] for i in d]     # 54.8 ms per loop
%timeit [list(i.values()).pop() for i in d]  # 81.8 ms per loop
Answered By: jpp

Using more_itertools.one is short, and also validates that there is a single entry

In [1]: from more_itertools import one
   ...: d = {"a":5}
   ...: one(d.values())
Out[1]: 5

Answered By: Alonme

is there a way to make the tuple assignment work for my usecase

v, *_ = d.values()

Extended unpacking will do the job in Python 3, failing with a ValueError: Not enough values to unpack if d is empty. Extended unpacking is not available in Python 2.

Answered By: Chris Keefe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.