简体   繁体   中英

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.

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]]

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM