Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #22610

Re: Is there a better way to do this snippet?

From Peter Otten <__peter__@web.de>
Subject Re: Is there a better way to do this snippet?
Date 2012-04-03 17:24 +0200
Organization None
References <52664090-0833-4ec2-af8b-326737dd67d1@w5g2000yqi.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.1282.1333466694.3037.python-list@python.org> (permalink)

Show all headers | View raw


python wrote:

> I played around with a few things and this works but was wondering if
> there was a better way to do this.
> My first thought was list comprehension but could not get a figure out
> the syntax.
> 
> tag23gr is a list of lists each with two items.
> g23tag is an empty dictionary when I run the for loop below.
> When is is complete each key is a graphic name who's values are a list
> of tags.
> 
> for item in tag23gr:
> ... 	value, key = tuple(item)
> ... 	if(g23tag.get(key)):

That should be

         if key in g23tag:

Your version means trouble for keys that evaluate to False in a boolean 
context, e. g. 0, False, None, "", (),...

> ... 		g23tag[key].append(value)
> ... 	else:
> ... 		g23tag[key] = [value]

from collections import defaultdict
g23tag = defaultdict(list)

for value, key in tag23gr:
    g23tag[key].append(value)

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Is there a better way to do this snippet? python <w.g.sneddon@gmail.com> - 2012-04-03 07:36 -0700
  Re: Is there a better way to do this snippet? Alain Ketterlin <alain@dpt-info.u-strasbg.fr> - 2012-04-03 17:02 +0200
    Re: Is there a better way to do this snippet? nn <pruebauno@latinmail.com> - 2012-04-03 08:37 -0700
      Re: Is there a better way to do this snippet? Alain Ketterlin <alain@dpt-info.u-strasbg.fr> - 2012-04-03 18:26 +0200
        Re: Is there a better way to do this snippet? nn <pruebauno@latinmail.com> - 2012-04-03 11:03 -0700
  Re: Is there a better way to do this snippet? Chris Angelico <rosuav@gmail.com> - 2012-04-04 01:09 +1000
  Re: Is there a better way to do this snippet? Peter Otten <__peter__@web.de> - 2012-04-03 17:24 +0200

csiph-web