Convert two lists into a dictionary

前端 未结 18 2516
囚心锁ツ
囚心锁ツ 2020-11-21 04:35

Imagine that you have:

keys = [\'name\', \'age\', \'food\']
values = [\'Monty\', 42, \'spam\']

What is the simplest way to produce the foll

18条回答
  •  半阙折子戏
    2020-11-21 05:03

    keys = ['name', 'age', 'food']
    values = ['Monty', 42, 'spam']
    index=np.arange(0,len(keys)-1)
    
    df=pd.DataFrame(list(zip(keys,values)), columns=['keys','values'])
    df.set_index('keys')
    print(df.head())
    
    data_dict = df.iloc[index].set_index('keys')['values'].to_dict() 
    print(data_dict)
    

    zip creates a generator of parallel values list() instantiates the full generator and passing that into the dataframe which converts the whole expression. resulting output:

    two lists:

        keys values
     0  name  Monty
     1   age     42
     2  food   spam
     
    

    Output: dictionary

     {'name': 'Monty', 'age': 42}
    

提交回复
热议问题