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]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With