Combining lists to dictionary

Gary Herron gherron at digipen.edu
Tue Nov 11 15:55:49 EST 2014


On 11/11/2014 12:43 PM, Denis McMahon 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.
>

Are you using python 2 or 3.  (It ought to be 3 :-) .)

In Python3, zip does not create a list, but rather an iterator which 
returns tuples.  Not clunky at all, but rather an efficient 
implementation of the loop which you hand coded in your other example.

 From help(zip):

class zip(object)
  |  zip(iter1 [,iter2 [...]]) --> zip object
  |
  |  Return a zip object whose .__next__() method returns a tuple where
  |  the i-th element comes from the i-th iterable argument.  The 
.__next__()
  |  method continues until the shortest iterable in the argument sequence
  |  is exhausted and then it raises StopIteration.

...


Gary Herron


-- 
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418




More information about the Python-list mailing list