[Baypiggies] list problem

Julian Snitow jsnitow at gmail.com
Thu Jul 22 13:21:51 CEST 2010


On Thu, Jul 22, 2010 at 4:07 AM, Brian Harring <ferringb at gmail.com> wrote:
>
> On Thu, Jul 22, 2010 at 09:53:46AM -0000, Vikram  wrote:
> >    Suppose you have the following list:
> >    >>> x =[['cat',10],['cat',20],['cat',30],['dog',5],['dog',1],['dog',3]]
> >    My problem is that i wish to obtain the following two dictionaries:
> >    xdictstart = {'cat':10, 'dog':1}
> >    xdictend = {'cat':30, 'dog':5}
> >    Any nice way to do the above? Thanks.
>
> Think you'd be better off stating the var names as min/max there,
> since that _seems_ to be what you want.  Could be wrong though.
>
> Suspect your main problem is you're not cheating enough in trying to
> solve it ;)
>
> xdictmin = dict(sorted(x, reverse=True))
> xdictmax = dict(sorted(x))
>
> ~brian

Here's my take on it, which avoids sorting.  I present it with the
caveat that I like Brian's solution better. :)

Julian

class Greatest(object):
    def __cmp__(self, other):
        return 1

class Least(object):
    def __cmp__(self, other):
        return -1

from collections import defaultdict

def more_or_less(x):
    least, greatest = defaultdict(Greatest), defaultdict(Least)

    for (key, value) in x:
        if least[key] > value:
            least[key] = value
        if greatest[key] < value:
            greatest[key] = value

    return [dict(x) for x in least, greatest]


More information about the Baypiggies mailing list