python dict, find value closest to x -


say have dict :

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

and have value

v = 3.19 

i want :

x = "the key value closest v" 

which result in

x = 'c' 

any hints on how approach this?

use min(iter, key=...)

target = 3.19 key, value = min(dict.items(), key=lambda (_, v): abs(v - target)) 

Comments

Popular posts from this blog

vb.net - Alternative to the T-SQL AS keyword -

php - MySQLi binding parameters in a prepared statement doesn't work unless inserted after "WHERE" -

ios - CFRelease causing crash in iPad application -