astroluv
astroluv

Reputation: 793

How to get more than one smallest /largest values of a dictionary?

Like if i create a dictionary using the following script:

r_lst = {}
for z in df.index:
  t = x.loc[0, 'sn']
  s = df.loc[z, 'rv']
  slope, intercept, r_value, p_value, std_err = stats.linregress(t,s)
  r_lst.setdefault(float(z),[]).append(float(r_value))

The resultant dictionary loos like this

{4050.32: [0.29174641574734467],
 4208.98: [0.20938901991887324],
 4374.94: [0.2812420188097632],
 4379.74: [0.28958742731611586],
 4398.01: [0.3309140298947313],
 4502.21: [0.28702220304639836],
 4508.28: [0.2170363811575936],
 4512.99: [0.29080133884942105]}

Now if i want to find the smallest or largest values of the dictionary then i just have to use this simple command min(r_lst.values()) or max(r_lst.values()).

What if i want the three lowest values or three highest values.? Then how can i get that? I saw some questions here but none of them answers what i'm asking for.

Upvotes: 2

Views: 628

Answers (2)

rahlf23
rahlf23

Reputation: 9019

Just use sorted():

sorted(r_lst.values())

Or in reverse order:

sorted(r_lst.values(), reverse=True)

So to get the 3 largest values:

sorted(r_lst.values(), reverse=True)[:3]

Yields:

[[0.3309140298947313], [0.29174641574734467], [0.29080133884942105]]

Upvotes: 2

jpp
jpp

Reputation: 164703

You can use heapq.nsmallest / heapq.nlargest:

import heapq

res = heapq.nsmallest(3, d.values())

# [[0.20938901991887324], [0.2170363811575936], [0.2812420188097632]]

To extract as a flat list, you can use itertools.chain:

from itertools import chain
import heapq

res = list(chain.from_iterable(heapq.nsmallest(3, d.values())))

# [0.20938901991887324, 0.2170363811575936, 0.2812420188097632]

These heapq solutions will have time complexity O((n-k)*log n) versus O(n log n) for solutions requiring a full sort.

Upvotes: 1

Related Questions