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 Inheritance
Python id()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python any()
Python Program to Catch Multiple Exceptions in One Line
Python open()
Python slice()
Python Program to Check the File Size
Python Program to Get Line Count of a File
Python String endswith()
Python Program to Count the Number of Digits Present In a Number
Python compile()
Python Program to Convert String to Datetime
Python Dictionary copy()
Python List insert()
Python exec()
Python Program to Sort Words in Alphabetic Order
Python Tuple index()
Python List count()
Python Global, Local and Nonlocal variables
Python Dictionary items()
Python Program to Differentiate Between type() and isinstance()
Python Objects and Classes
Python Program to Safely Create a Nested Directory
Deep Learning with Python - Francois Chollet
Python globals()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Modules
Python next()
Python String replace()
Python break and continue
Python Program to Check Whether a String is Palindrome or Not