Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get single value from dict with single entry?

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?

like image 979
GhostCat Avatar asked Apr 26 '17 08:04

GhostCat


People also ask

How do you find the value of one in a dictionary?

Use dict. get() to get the default value for non-existent keys. You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist.

How do you get a single key from a value in Python?

Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.


2 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.

like image 157
B. Barbieri Avatar answered Sep 25 '22 12:09

B. Barbieri


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 
like image 31
jpp Avatar answered Sep 23 '22 12:09

jpp