Is there a way to find the 2 outside numbers in a dictionary of "Name": Number pairs from an input number

Question:

Sorry if the title is convuluted. Tried my best haha.

An example for easier understanding of the question:

levels = {"Level 1": 3.9, "Level 2": 4.5, "Level 3": 5.6, "Level 4": 9.2, "Level 5": 11.93}

current_number = 6.3

def find_upper_lower(current_number, levels):
    ###something here

    upper_level = {"Level 4": 9.2}
    lower_level = {"Level 3": 5.6}

    return {"upper_level": upper_level, "lower_level": lower_level}

print(find_upper_lower(current_number, levels))

### Results
### {'upper_level': {'Level 4': 9.2}, 'lower_level': {'Level 3': 5.6}}

So essentially I’m looking to find the two nearest numbers (above and below the current number) and return them but with the whole dictionary item, not just the number. I think a way to do this if it was a list would be to add the current number to the list of items, then sort it and then find the index of the number inserted, and then add and minus 1 to the index to get the items before and after the number inserted – but I believe this would only work with a list and I need to somehow keep the "keys" in the dictionary, not just the values.

Thank you for any help – if you need me to explain anything more no problem just let me know.

Asked By: Jeffrey Winger

||

Answers:

you can use the min and max function with an ordering function (lambda) to get the selected keys and then assemble your resulting dictionary from those keys:

highKey = min(levels,key=lambda k:(levels[k]<=current_number,levels[k]-current_number))
lowKey  = max(levels,key=lambda k:(levels[k]<current_number,levels[k]-current_number))

result = {"upper_level":{highKey:levels[highKey]},
          "lower_level":{lowKey:levels[lowKey]}}

{'upper_level': {'Level 4': 9.2}, 'lower_level': {'Level 3': 5.6}}

The key lambda supplied to min and max return a tuple with a boolean as their first entry. This allow the functions to exclude the subset of values that are not eligible by placing them at the other end of the value order (True being greater than False)

Answered By: Alain T.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.