Thisisstackoverflow
Thisisstackoverflow

Reputation: 261

How do I find the top level KEY of the lowest positive VALUE from a particular SUBKEY?

My data looks like this:

{   
    'test1462477941.log': {   'end_diff': 537,
                               'file_epoch': 1462477941,
                               'start_diff': -33},
    'test1462478161.log': {   'end_diff': 317,
                               'file_epoch': 1462478161,
                               'start_diff': 284},
    'test1462478346.log': {   'end_diff': 132,
                               'file_epoch': 1462478346,
                               'start_diff': 99},
}

What I want to do is find the lowest, positive "start_diff" value in any of the keys and print the relative top level key (the filename). The data structure is throwing me off a bit though.

If using the data above, it shoud find and print out:

test1462478346.log

Is there an elegant way to do this? If not, I'll take anything

Upvotes: 0

Views: 57

Answers (2)

JRazor
JRazor

Reputation: 2817

Use filter for removing non positive and min with key for search:

a = {
    'test1462477941.log': {'end_diff': 537,
                           'file_epoch': 1462477941,
                           'start_diff': -33},
    'test1462478161.log': {'end_diff': 317,
                           'file_epoch': 1462478161,
                           'start_diff': 284},
    'test1462478346.log': {'end_diff': 132,
                           'file_epoch': 1462478346,
                           'start_diff': 99},
}

only_positive_start_diff = filter(lambda x: x[1]['start_diff'] > 0, a.items())
min_start_diff = min(only_positive_start_diff, key=lambda x: x[1]['start_diff'])

print min_start_diff[0]  # Min log file

Without lambda it's look like:

def only_positive(x):
    return x[1]['start_diff'] > 0

def min_start(x):
    return x[1]['start_diff']

only_positive_start_diff = filter(only_positive, a.items())
min_start_diff = min(only_positive_start_diff, key=min_start)

print min_start_diff[0]

Upvotes: 1

Lei Shi
Lei Shi

Reputation: 767

This is a solution using built-in function reduce:

import sys
filename, start_diff = reduce(
    lambda curMin, item:
        curMin if item[1]['start_diff']<0 or item[1]['start_diff']>curMin[1] else (item[0], item[1]['start_diff']),
    inputDict.iteritems(),
    ('not_found.log', sys.maxint))

print filename

Please note that the code is written with Python 2.7. If you use Python 3.x, then you should find reduce function in functools, and dict.iteritems() has been changed to dict.items().

Upvotes: 1

Related Questions