I have a dictionary myDict
{'1': 5, '2': 13, '3': 23, '4': 17}
I'm using this code, that has served me well, in order to find the key/value in myDict
closest to a targetVal
answer = key, value = min(myDict.items(), key=lambda (_, v): abs(v - targetVal))
Assuming targetVal
is 14
, answer
returns:
('2': 13)
What I need to do now, is deal with identical values in myDict
. For example, if myDict
was now:
{'1': 5, '2': 13, '3': 23, '4': 13}
I need both those key/value pairs with the value 13
. In instances when the code (above) finds the closest value in myDict
, and that value happens to appear more than once, i'd like to create a new dictionary. In this case, answer
would return:
{'2': 13, '4': 13}
Is it possible to update the way answer
is being found to account for instances when the closest value appears more than once?
Find the minimum value first, then filter your dict
.
>>> d = {'1': 5, '2': 13, '3': 23, '4': 13}
>>> target = 13
>>> min_ = min(d.itervalues(), key=lambda v: abs(v - target))
>>> {k:v for k,v in d.iteritems() if v == min_}
{'2': 13, '4': 13}
As you found, min
provides only one item which satisfies the minimum condition. You can construct a one-pass solution via a manual loop:
from math import inf
myDict = {'1': 5, '2': 13, '3': 23, '4': 13}
targetVal = 14
res = {}
diff = inf
for k, v in myDict.iteritems():
current_diff = abs(v - targetVal)
if current_diff <= diff:
if current_diff < diff:
diff = current_diff
res.clear()
res.update({k: v})
print(res)
# {'2': 13, '4': 13}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.