Create a dictionary with list comprehension

前端 未结 14 1990
灰色年华
灰色年华 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条回答
  •  -上瘾入骨i
    2020-11-21 07:47

    Use a dict comprehension:

    {key: value for (key, value) in iterable}
    

    Note: this is for Python 3.x (and 2.7 upwards). Formerly in Python 2.6 and earlier, the dict built-in could receive an iterable of key/value pairs, so you can pass it a list comprehension or generator expression. For example:

    dict((key, func(key)) for key in keys)
    

    In simple cases you don't need a comprehension at all...

    But if you already have iterable(s) of keys and/or values, just call the dict built-in directly:

    1) consumed from any iterable yielding pairs of keys/vals
    dict(pairs)
    
    2) "zip'ped" from two separate iterables of keys/vals
    dict(zip(list_of_keys, list_of_values))
    

提交回复
热议问题