Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dict, find value closest to x

say I have a dict like this :

d = {'a': 8.25, 'c': 2.87, 'b': 1.28, 'e': 12.49}

and I have a value

v = 3.19

I want to say something like :

x = "the key with the value CLOSEST to v"

Which would result in

x = 'c'

Any hints on how to approach this?

like image 201
jason Avatar asked Aug 12 '13 21:08

jason


4 Answers

Use min(iter, key=...)

target = 3.19
key, value = min(dict.items(), key=lambda (_, v): abs(v - target))
like image 82
Eric Avatar answered Oct 25 '22 12:10

Eric


You can do this:

diff = float('inf')
for key,value in d.items():
    if diff > abs(v-value):
        diff = abs(v-value)
        x = key

print x

which gives 'c'

You can also use min to do the job:

x = min(((key, abs(value-v)) for key,value in d.items()), key = lambda(k, v): v)[0]
like image 42
jh314 Avatar answered Oct 25 '22 12:10

jh314


Not sure what you want it to do if two values are equally far from the target, but if that's ever an issue, you could use something like this

min_diff = min(abs(v - target) for v in d.values())
closest_keys = [k for k, v in d.items() if abs(v - target) == min_diff]
like image 1
Stuart Avatar answered Oct 25 '22 12:10

Stuart


for python3, use this:

target = 3.19    
key, value = min(d.items(), key=lambda kv : abs(kv[1] - target))

if you just want the key of the value that's closest to target:

value = min(d.items(), key=lambda kv : abs(kv[1] - target))[0]
like image 1
Bismo Funyuns Avatar answered Oct 25 '22 13:10

Bismo Funyuns