Create a dictionary with list comprehension

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

    In Python 2.7, it goes like:

    >>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
    >>> dict( zip( list1, list2))
    {'a': 1, 'c': 3, 'b': 2}
    

    Zip them!

提交回复
热议问题