Re: Is there something similar to list comprehension in dict?

Discussion in 'Python' started by Patrick Sabin, Nov 20, 2009.

  1. Peng Yu wrote:
    > I'm wondering if there is something similar to list comprehension for
    > dict (please see the example code below).


    Do you mean something like this:

    >>> {i:i+1 for i in [1,2,3,4]}

    {1: 2, 2: 3, 3: 4, 4: 5}

    This works in python3, but not in python2

    - Patrick
    Patrick Sabin, Nov 20, 2009
    #1
    1. Advertising

  2. Patrick Sabin

    Paul Rudin Guest

    Patrick Sabin <> writes:

    > Peng Yu wrote:
    >> I'm wondering if there is something similar to list comprehension for
    >> dict (please see the example code below).

    >
    > Do you mean something like this:
    >
    >>>> {i:i+1 for i in [1,2,3,4]}

    > {1: 2, 2: 3, 3: 4, 4: 5}
    >
    > This works in python3, but not in python2


    Of course in python 2 you can do:

    >>> dict((i, i+1) for i in [1,2,3,4])

    {1: 2, 2: 3, 3: 4, 4: 5}
    Paul Rudin, Nov 20, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mike42
    Replies:
    21
    Views:
    17,325
    Chris Uppal
    Nov 14, 2005
  2. Bo Peng
    Replies:
    31
    Views:
    786
    Ron Adam
    Jun 30, 2005
  3. Drew
    Replies:
    19
    Views:
    1,328
    Duncan Booth
    Mar 15, 2007
  4. Vedran Furac(
    Replies:
    4
    Views:
    316
    Marc 'BlackJack' Rintsch
    Dec 19, 2008
  5. Peng Yu
    Replies:
    8
    Views:
    336
    Steven D'Aprano
    Nov 20, 2009
Loading...

Share This Page