Create a dictionary with list comprehension

前端 未结 14 1996
灰色年华
灰色年华 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 07:57

    In Python 3 and Python 2.7+, dictionary comprehensions look like the below:

    d = {k:v for k, v in iterable}
    

    For Python 2.6 or earlier, see fortran's answer.

提交回复
热议问题