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?
Use min(iter, key=...)
target = 3.19
key, value = min(dict.items(), key=lambda (_, v): abs(v - target))
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]
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With