building a dict

rurpy at yahoo.com rurpy at yahoo.com
Sat Mar 13 11:26:59 EST 2010


On Mar 13, 9:13 am, ru... at yahoo.com wrote:
> On Mar 13, 8:28 am, Patrick Maupin <pmau... at gmail.com> wrote:
>
>
>
> > On Mar 13, 9:05 am, vsoler <vicente.so... at gmail.com> wrote:
>
> > > Say that "m" is a tuple of 2-tuples
>
> > > m=(('as',3), ('ab',5), (None, 1), ('as',None), ('as',6))
>
> > > and I need to build a "d" dict where each key has an associated list
> > > whose first element is the count, and the second is the sum. If a 2-
> > > tuple contains a None value, it should be discarded.
>
> > > The expected result is:
> > > d={'as':[2, 9], 'ab': [1,5]}
>
> > > How should I proceed? So far I have been unsuccessful. I have tried
> > > with a "for" loop.
>
> > Post your first try at a for loop, and people might be willing to
> > point out problems, but this is such a basic for loop that it is
> > unlikely that anybody is going to write your ENTIRE homework for you.
>
> This is probably what you (OP) were trying to come up with?
> [untested]
>
> d = {}
> for item in m:
>     key = m[0];  value = m[1]
>     if key is None or value is None: continue
>     if key not in dict:
>         d[key] = [value]
>     else:
>         d[key].append (value)
>
> You can replace the
>   for item in m:
>       key = m[0];  value = m[1]
> above with
>   for key, value in m:
> which is a little nicer.
>
> However, as other responses point out, when you want
> to "accumulate" results in a dict, collections.defaultdict
> should pop into your mind first.

Oops, didn't read very carefully, did I?

That should be:
d = {}
for item in m:
    key = m[0];  value = m[1]
    if key is None or value is None: continue
    if key not in dict:
        d[key] = [1, value]
    else:
        d[key][0] += 1
        d[key][1] += value




More information about the Python-list mailing list