Is there a better way to do this snippet?

Peter Otten __peter__ at web.de
Tue Apr 3 11:24:46 EDT 2012


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)





More information about the Python-list mailing list