Combining lists to dictionary
Roy Smith
roy at panix.com
Tue Nov 11 20:06:47 EST 2014
In article <m3tscl$f1e$2 at dont-email.me>,
Denis McMahon <denismfmcmahon at 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.
I would definitely use the first one. It's so much easier to read. If
I was worried that the lists might be so long that the cost of building
the intermediate list mattered, I'd use izip() instead of zip().
More information about the Python-list
mailing list