Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80563

Re: Combining lists to dictionary

Date 2014-11-11 12:55 -0800
From Gary Herron <gherron@digipen.edu>
Subject Re: Combining lists to dictionary
References <m3tscl$f1e$2@dont-email.me>
Newsgroups comp.lang.python
Message-ID <mailman.15691.1415739909.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Combining lists to dictionary Denis McMahon <denismfmcmahon@gmail.com> - 2014-11-11 20:43 +0000
  Re: Combining lists to dictionary Gary Herron <gherron@digipen.edu> - 2014-11-11 12:55 -0800
  Re: Combining lists to dictionary Rob Gaddi <rgaddi@technologyhighland.invalid> - 2014-11-11 13:42 -0800
  Re: Combining lists to dictionary Roy Smith <roy@panix.com> - 2014-11-11 20:06 -0500
  Re: Combining lists to dictionary Ben Finney <ben+python@benfinney.id.au> - 2014-11-12 12:16 +1100
  Re: Combining lists to dictionary Dave Angel <davea@davea.name> - 2014-11-12 01:13 -0500

csiph-web