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'}
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}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With