On Tue, 11 Nov 2014 20:43:01 +0000 (UTC)
Denis McMahon <denismfmcma...@gmail.com> wrote:

> Hi
> 
> Given x,y are a lists of keys and value that I wish to combine to a 
> dictionary, such that x[n] is the key for value y[n], which is preferred:
> 
> z = {a:b for (a,b) in zip(x,y)}
> z = {x[n]:y[n] for n in range(min(len(x),len(y)))}
> 
> The zip feels more elegant, but it seems clunky to use the zip method to 
> create a list of tuples just to split them up into key:value pairs. 
> However the zip method handles the inequal length list problem. Granted 
> it would probably be advisable to check that x and y are the same length 
> before starting anyway.
> 
> -- 
> Denis McMahon, denismfmcma...@gmail.com

To add to what Gary said, the explicit dict() init knows how to handle
an iterable that emits pairs of data.  So you can simplify further down to:

z = dict(zip(x, y))

If you're running Python2, and really that concerned about the extra
memory used by zip returning a list rather than an iterator, you can
use itertools.izip

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to