1
def get_nearest_less_element(d, k):
    return (min(value for value in map(float, d.values()) if value >= k))

So, d is a dict() and k is float, this function returns me the correct value, but can I return the corresponding key of that value from this function?

MrRobot9
  • 2,402
  • 4
  • 31
  • 68
  • Simply iterate over the dictionary using d.items(), and there you have access to key and value. At the end, you would have both key and value. Return them as a tuple. – vb_rises Sep 10 '19 at 01:24
  • Possible duplicate of [Finding key from value in Python dictionary:](https://stackoverflow.com/questions/7657457/finding-key-from-value-in-python-dictionary) – Mars Sep 10 '19 at 01:26
  • The title question is a duplicate, the thing you actually want to know is how to iterate key AND value, which is a different question – Mars Sep 10 '19 at 01:28

4 Answers4

5
def get_nearest_less_element(d, k):
    return min(key for key, value in d.items() if float(value) >= k)
Deepstop
  • 3,627
  • 2
  • 8
  • 21
4

Instead of iterating over values with dict.values(), iterate over both keys and values with dict.items() which yields (key, value) pairs.

def get_nearest_less_element(d, k):
    return min(key for key, value in d.items() if float(value) >= k)
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
1

If key is what you want:

def get_nearest_less_element(dict_obj, threshold):
    min_value, min_key = min(
        ((value, key) for key, value in dict_obj.items() if float(value) < threshold),
        key=lambda value_key: float(value_key[0])
    )
    print('min_value =', min_value, ', min_key =', min_key)
    return min_key

Basically, what I did is similar to @MrRobot9, but I sorted the pairs of (value, key) based on the values. Note that because I put the value before the key, the sorting will be based on value, there is no need for the key= part, but I just put it there to be more explicit.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
0

If you want to return the neighbor's , consider this solution:

def get_nearest_less_element2(d, k):
    dict_nearest = {value:key for key,value in d.items() if value >= float(k)}
    nearest_index = min(dict_nearest)
    nearest_value = dict_nearest[nearest_index]
    return nearest_index, nearest_value

Moreover, with the following simple test you can check the equivalence of the results obtained from your old function and the new one:

d={1:11, 100:333, 40:44, 9:21, 4:99, 88:31, 7:77}
test_res = []

for k in range(0, 100, 5):
    test_res.append(get_nearest_less_element(d,k) == get_nearest_less_element2(d,k)[0])

print(all(test_res))
# True
Massifox
  • 4,369
  • 11
  • 31