Create a dictionary with list comprehension

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

    Just to throw in another example. Imagine you have the following list:

    nums = [4,2,2,1,3]
    

    and you want to turn it into a dict where the key is the index and value is the element in the list. You can do so with the following line of code:

    {index:nums[index] for index in range(0,len(nums))}
    

提交回复
热议问题