Finding lowest value in dictionary of objects, how?
Steven Bethard
steven.bethard at gmail.com
Mon Nov 19 12:03:17 EST 2007
Boris Borcic wrote:
> davenet wrote:
>> Hi,
>>
>> I'm new to Python and working on a school assignment.
>>
>> I have setup a dictionary where the keys point to an object. Each
>> object has two member variables. I need to find the smallest value
>> contained in this group of objects.
>>
>> The objects are defined as follows:
>>
>> class Block:
>> def __init__(self,addr):
>> self.addr = addr
>> self.age = 0
>>
>> My dictionary is defined as:
>> blocks = {}
>>
>> I have added 1000 (will hold more after I get this working) objects. I
>> need to find the lowest age in the dictionary. If there is more than
>> one age that is lowest (like if several of them are '1', etc), then I
>> can just pick randomly any that equal the lowest value.
>
> >>> help(min)
> Help on built-in function min in module __builtin__:
>
> min(...)
> min(iterable[, key=func]) -> value
> min(a, b, c, ...[, key=func]) -> value
>
> With a single iterable argument, return its smallest item.
> With two or more arguments, return the smallest argument.
>
> >>> def f(x) : return 3*x**2+10*x-4
>
> >>> min(f(x) for x in range(-100,100))
> -12
> >>> min(range(-100,100), key=f)
> -2
> >>> f(-2)
> -12
I'd like to second this one just so it doesn't get lost among all the
other responses. You definitely want to look into the key= argument of
min(). Your key function should look something like::
def key(block):
# return whatever attribute of block you care about
Then just modify this code::
lowest = min(self.blocks.values())
to use the key= argument as well. I don't think you need the list
comprehension at all.
STeVe
More information about the Python-list
mailing list