Create a dictionary with list comprehension

前端 未结 14 1995
灰色年华
灰色年华 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:04

    Python version < 2.7(RIP, 3 July 2010 - 31 December 2019), do the below:

    d = dict((i,True) for i in [1,2,3])
    

    Python version >= 2.7, do the below:

    d = {i: True for i in [1,2,3]}
    

提交回复
热议问题