简体   繁体   中英

Quickest way to get dictionary key that is closest to 1 in Python

Hi I wanted to ask if this is the quickest and taking the least resources way to get value closest to 1 in dictionary or is there better, more effective way of doing this.

import operator

dct = {"a": 0.1, "b": 0.2, "c": 0.7, "d": 1, "e": 0.5}

sorted_orders = sorted(dct.items(), key=operator.itemgetter(1))
sorted_orders = str(sorted_orders.pop()[:1])
a = len(sorted_orders) - 3
sorted_orders = sorted_orders[2:a]
print sorted_orders

Desired output is contents of key closest to 1 here: d

This is how I would do it:

closest = sorted(dct.values(), key=lambda x: abs(1-x))[0]

I sort the items with a key that gives the distance between the number and 1 . ( abs(1-x1) ). The first item, therefore, is the value that is closest to 1 . You could use min() as in the answer by Gábor Erdős, but if you want to know the whole order, use this.

This should do it

min(list(dct.values()), key=lambda x: abs(x - 1))

Notes:

  1. This method works for lists as well

  2. This is not the most efficient way. A faster approach would be to use bisect

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