Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #22607
| References | <52664090-0833-4ec2-af8b-326737dd67d1@w5g2000yqi.googlegroups.com> |
|---|---|
| Date | 2012-04-04 01:09 +1000 |
| Subject | Re: Is there a better way to do this snippet? |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1280.1333465778.3037.python-list@python.org> (permalink) |
On Wed, Apr 4, 2012 at 12:36 AM, python <w.g.sneddon@gmail.com> wrote: > for item in tag23gr: > ... value, key = tuple(item) > ... if(g23tag.get(key)): > ... g23tag[key].append(value) > ... else: > ... g23tag[key] = [value] Simple enhancement: Use setdefault. Instead of the if, just use: g23tag.setdefault(key,[]).append(value) That'll cover both cases in one. You can leave off the explicit tuple construction; if item is a two-element list, you can unpack it directly. You can also embed that straight into your for loop: for value,key in tag23gr: Do both and you cut your loop down to two lines. Cool! :) Chris Angelico
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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