Is there a better way to do this snippet?

Chris Angelico rosuav at gmail.com
Tue Apr 3 11:09:35 EDT 2012


On Wed, Apr 4, 2012 at 12:36 AM, python <w.g.sneddon at 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



More information about the Python-list mailing list