Create a dictionary with list comprehension

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

    This code will create dictionary using list comprehension for multiple lists with different values that can be used for pd.DataFrame()

    #Multiple lists 
    model=['A', 'B', 'C', 'D']
    launched=[1983,1984,1984,1984]
    discontinued=[1986, 1985, 1984, 1986]
    
    #Dictionary with list comprehension
    keys=['model','launched','discontinued']
    vals=[model, launched,discontinued]
    data = {key:vals[n] for n, key in enumerate(keys)}
    

    enumerate will pass n to vals to match each key with its list

提交回复
热议问题