Map two lists Python
Ngày đăng:
08/01/2022
Trả lời:
0
Lượt xem:
159
Python Program to Convert Two Lists Into a DictionaryIn this example, you will learn to convert two lists into a dictionary. Show To understand this example, you should have the knowledge of the following Python programming topics:
Example 1: Using zip and dict methodsindex = [1, 2, 3] languages = ['python', 'c', 'c++'] dictionary = dict(zip(index, languages)) print(dictionary)Output {1: 'python', 2: 'c', 3: 'c++'}We have two lists: index and languages. They are first zipped and then converted into a dictionary.
Example 2: Using list comprehensionindex = [1, 2, 3] languages = ['python', 'c', 'c++'] dictionary = {k: v for k, v in zip(index, languages)} print(dictionary)Output {1: 'python', 2: 'c', 3: 'c++'}This example is similar to Example 1; the only difference is that list comprehension is being used for first zipping and then { } for converting into a dictionary. Learn more about list comprehension at Python List Comprehension. |