In this example, you will learn to convert two lists into a dictionary.
To understand this example, you should have the knowledge of the following Python programming topics:
- Python Dictionary
- Python zip()
1. Example 1: Using zip and dict methods
index = [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.
- The
zip()function takes iterables (can be zero or more), aggregates them in a tuple, and returns it. - Likewise,
dict()gives the dictionary.
2. Example 2: Using list comprehension
index = [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.
Related posts:
Python String expandtabs()
Python sorted()
Python Program to Find Numbers Divisible by Another Number
Python Program to Randomly Select an Element From the List
Python id()
Python Set difference_update()
Python Program to Make a Simple Calculator
Python List append()
Python compile()
Python property()
Python if...else Statement
Deep Learning with Python - Francois Cholletf
Python String replace()
Python filter()
Python Program to Find Armstrong Number in an Interval
Python divmod()
Python frozenset()
Python String swapcase()
Python Program to Check if a Number is Positive, Negative or 0
Python List
Python String find()
Python Program to Check Leap Year
Python Program to Delete an Element From a Dictionary
Python Program to Count the Number of Digits Present In a Number
Python Program to Calculate the Area of a Triangle
Python Program to Convert String to Datetime
Python String ljust()
Python Program to Find the Size (Resolution) of a Image
Python Program to Check Whether a String is Palindrome or Not
Python range()
Python List sort()
Python repr()