Issue
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?
Solution
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}
Answered By - timgeb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.