Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert data from two lists to dict with for loop [duplicate]

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
like image 892
Python Avatar asked Jul 03 '18 16:07

Python


2 Answers

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'}
like image 114
fordy Avatar answered Oct 15 '22 19:10

fordy


Use zip - https://www.programiz.com/python-programming/methods/built-in/zip.

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

numbers_dict = dict(zip(name_list, num_list))

then print(numbers_dict) gives {'one': 1, 'two': 2, 'three': 3, 'four': 4}.

like image 2
PythonParka Avatar answered Oct 15 '22 18:10

PythonParka