insert data from two lists to dict with for loop

  • A+
Category:Languages

I tried this:

numbers_dict = dict() num_list = [1,2,3,4] name_list = ["one","two","three","four"] numbers_dict[name for name in name_list] = num for num in num_list 

And as a result I got this exception:

File "<stdin>", line 1 numbers_dict[name for name in name_list] = num for num in num_list 

 


You don't need to explicitly loop. You can use zip to join your two lists and then wrap it in a dict for the result you're looking for:

dict(zip(num_list, name_list))  >>> {1: 'one', 2: 'two', 3: 'three', 4: 'four'} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: