Issue
I have a dictionary myDict
{'1': 5, '2': 15, '3', 50}
I have a targetNumber of 12
I'm using this code to find the number closest to 12
in myDict
answer = key, value = min(myDict.items(), key=lambda (_, v): abs(v - targetNumber))
answer
returns ('2', 15)
That's the key/value that I want, but what I really need now is the 2
.
When I print myDict[key]
, it returns 15
How can I return what I believe was the key, but now that it is in that tuple, i'm not sure exactly what i'm dealing with.
I'd like to end up with:
2
Solution
Unpack "answer":
Key, Value = answer
or use
Key = Answer[ 0 ]
Value = Answer{ 1 ]
Answered By - user1459519
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.