Can python create a dictionary from a list comprehension?
Peter Otten
__peter__ at web.de
Mon May 28 05:04:07 EDT 2007
half.italian at gmail.com wrote:
> Do you think we just shouldn't use list comprehensions to build
> dictinaries at all? Or is Stefan's solution acceptable (and pythonic)?
Use list comprehensions where you need the resulting list; if you want
nothing but the side effects, use a for loop.
[Stefan Sonnenberg-Carstens]
> a = [1,2,3,4,5,6,7,8,9,10]
> aDict = dict([(x,x+1) for x in a if x%2==0])
Stefan's example meets the above criterion, so yes, it's acceptable. In
Python 2.5 you would use a generator expression, though:
aDict = dict((x, x+1) for x in a if x % 2 ==0)
Peter
More information about the Python-list
mailing list