Create a dictionary with list comprehension

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

    To add onto @fortran's answer, if you want to iterate over a list of keys key_list as well as a list of values value_list:

    d = dict((key, value) for (key, value) in zip(key_list, value_list))
    

    or

    d = {(key, value) for (key, value) in zip(key_list, value_list)}
    

提交回复
热议问题