Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find the closest, positive value, from a dictionary's item's keys? (Python)

Assuming I have a dictionary in this structure:

data = {
    '111': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 301},
    '112': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 302},
    '113': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 377},
    '114': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 311},
    '115': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 314},
    '116': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 306},
    '117': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 387}
    #...
}

Based on ‘c’ key, I’m looking for a way to return a dict item from which, a given input (e.g ‘312’), is the closest positive value in that key.

E.g:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

input = 312

expected result:

>>> {'115': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 314}}

The script would ignore negative values (for example, item ‘114’ ‘c’ key is 311, which is closer to 312, but ignored since it’s less than the input number).

I’ve tried looking on google for ways to do this, but the only results I got were examples for the closest positive or negative, while the value I’m looking for has to be positive.

>Solution :

You can use a generator expression to filter the keys with a c that is below the target and min to find the closet key:

target = 312

closest_key_above = min((k for k, d in data.items() if d['c']>target),
                        key=lambda k: data[k]['c']-target)

Output:

'115'

To get the dictionary:

{closest_key_above: data[closest_key_above]}
# {'115': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 314}}

as a function

def find_closest(data, target):
    key = min((k for k, d in data.items() if d['c']>target),
              key=lambda k: data[k]['c']-target)
    return {key: data[key]}

find_closest(data, 307)
# {'114': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 311}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading