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?
target = 3.19 key, value = min(dict.items(), key=lambda (_, v): abs(v - target))
Comments
Post a Comment