Python - Combine two list with zip function

Introduction

To zip the lists and step through them in parallel with a for loop.

Demo

Code:
 keys = ['test', 'eggs', 'toast'] 
 vals = [1, 3, 5] # from   ww  w .j ava  2 s . c  o m
                                                                                      
 print( list(zip(keys, vals)) )
                                                                                      
 D2 = {} 
 for (k, v) in zip(keys, vals): D2[k] = v 
                                                                                      
 print( D2 )

Result

You can pass the zipped keys/values lists to the built-in dict constructor call:

Demo

keys = ['test', 'eggs', 'toast'] 
vals = [1, 3, 5] # from  ww w. j  a  v a2  s.  c o  m

D3 = dict(zip(keys, vals)) 
print( D3 )

Result

Related Topic