What is the better(neater) way to find the largest list range in dictionary of lists

Viewed 106

I have the dict which consists of lists as values. List is len(2) representing the range of an array:

new_dict = {0: [0, 7], 1:[15, 21], 2:[-5, 3]}

I need to find the key with list that has the largest range i.e. largest list[1] - list[0]

I've done it this way and it works fine, but I am assuming it can be done in simpler, or more pythonic way.

largest = float("-inf")
largest_list = []
for key in new_dict.keys():
        temp = new_dict[key][1] - new_dict[key][0]
        if temp > largest:
            largest = temp
            largest_list = new_dict[key]
2 Answers

You could use max() with a custom key function:

>>> new_dict = {0: [0, 7], 1:[15, 21], 2:[-5, 3]}
>>> max(new_dict.items(), key=lambda x: x[1][1] - x[1][0])[0]
2

Having a little fun...

>>> import operator
>>> min(new_dict, key=lambda k: operator.sub(*new_dict[k]))
2

or

>>> max(new_dict, key=lambda k: len(range(*new_dict[k])))
2

or

>>> min(new_dict, key=lambda k: int.__sub__(*new_dict[k]))
2
Related