GingerDom
GingerDom

Reputation: 113

Finding the values in a dictionary which are closest to a given number

New to python 3 and trying to play about with some dictionaries.

What I'm going for is I have a dictionary with a lot of keys e.g. {Dog : 2, Cat : 5, Fish : 3} but its really big. Now I'm given a value e.g. 2 and I want it to return ten dictionary elements have have the value closest to 2.

Any ideas if it is possible to do this, and if so can some one point me on the right path?

Sorry I have just realised that actually all I want to be returned is the key.

Upvotes: 0

Views: 78

Answers (1)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19219

Yes. With Python, use heapq.nsmallest

import heapq
d = <iterable of many key-value pairs>

def f(pair): return abs(pair[1]-2)

least10 = heapq(10, d, key=f)

For more general answers, search web for 'n smallest'. There are related answers already on SO.

Upvotes: 2

Related Questions