Create a dictionary with list comprehension

前端 未结 14 2406
灰色年华
灰色年华 2020-11-21 07:07

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydi         


        
14条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 08:01

    In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

    >>> ts = [(1, 2), (3, 4), (5, 6)]
    >>> dict(ts)
    {1: 2, 3: 4, 5: 6}
    >>> gen = ((i, i+1) for i in range(1, 6, 2))
    >>> gen
     at 0xb7201c5c>
    >>> dict(gen)
    {1: 2, 3: 4, 5: 6}
    

提交回复
热议问题