#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0

    Using zip to create a dict from 2 arrays


    I understand how to do this:

    Code:
    >>> p = [1, 2, 3]
    >>> q = ['a', 'b', 'c']
    >>> d = dict(zip(p, q))
    but messing around with this I found

    Code:
    >>> p = [1, 2, 3]
    >>> q = ['a', 'b', 'c']
    >>> z = zip(p, q)
    >>> d = dict(z)
    doesn't work. It creates an empty dict. Could anyone explain why this is, it feels like I have missed something important.

    Python 3.3
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    606
    Rep Power
    65
    Which version of Python are you using?
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    Works fine for me. Also on 3.3:
    Code:
    >>> p = [1, 2, 3]
    >>> q = ['a', 'b', 'c']
    >>> z = zip(p, q)
    >>> d = dict(z)
    >>> d
    {1: 'a', 2: 'b', 3: 'c'}
    Are you entirely certain you're not doing anything else in between? In particular, are you doing something with the zip object before passing it to dict? The iterator returned by zip yields each pair only once, so if you, for instance, try to make two dicts from it, the second one will be empty.
  6. #4
  7. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    606
    Rep Power
    65
    zip() in Python 3 gives a generator object

    if you want to display z and use list(z) then z is consumed and needs to be regenerated

    might be something you didn't tell us
    Last edited by Dietrich; July 5th, 2013 at 06:12 PM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0
    Yes you are absolutely right, thank you. I was using list() to check z before I made a dict().

    Easy trap!

IMN logo majestic logo threadwatch logo seochat tools logo