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

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -