Create a dictionary with list comprehension

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

    You can create a new dict for each pair and merge it with the previous dict:

    reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})
    

    Obviously this approaches requires reduce from functools.

提交回复
热议问题