Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get greatest key in dictionary but lower than a variable

Tags:

python

Given a dictionary and a variable like this:

dic = {0 : 'some', 10 : 'values', 20 : 'whatever'}
var = 14

I want to get the value from the dictionary where the key is the greatest but lower or equal to the variable. I don't know if that's clear but in this case I am looking for 10.

I've come up with this function but I wanted to know if there is an easier way to do it as I am pretty new to python.

def get_greatest_key(dic, var):
    # if the key exists no need to search
    if var in dic:
        return dic[var]
    else:
        # create a list with all the keys sorted in reverse 
        l = sorted(dic, key=dic.get)
        i = 0
        while i < len(l):
            # parse the list
            if l[i] <= var:
                return dic[l[i]]
            i += 1
        # by default we return the last element in the dictionary
        return dic[l[len(l) - 1]]
like image 560
romainberger Avatar asked Jan 13 '23 16:01

romainberger


1 Answers

If you want the maximum key which is less than or equal to var, then you can pass a generator expression to the max function:

>>> dic = {0 : 'some', 10 : 'values', 20 : 'whatever'}
>>> var = 14
>>> max(k for k in dic if k <= var)
10

with corresponding value

>>> dic[max(k for k in dic if k <= var)]
'values'

You can decide what to do with the ValueError thrown if the argument to max is empty as you see fit.

like image 148
DSM Avatar answered Jan 28 '23 04:01

DSM