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 Program to Create a Long Multiline String
Python pass statement
Python timestamp to datetime and vice-versa
Python Program to Generate a Random Number
Python Data Structures and Algorithms - Benjamin Baka
Python Exception Handling Using try, except and finally statement
Python super()
Python Function Arguments
Python Dictionary copy()
Python String maketrans()
Python id()
Python RegEx
Python Dictionary
Python Keywords and Identifiers
Python list()
Python time Module
Python Set difference_update()
Python Program to Find Armstrong Number in an Interval
Python Program to Slice Lists
Python Program to Add Two Matrices
Python Program to Check Armstrong Number
Python Operator Overloading
Python Program to Merge Two Dictionaries
Python Global, Local and Nonlocal variables
Python Program to Parse a String to a Float or Int
Python Program to Differentiate Between del, remove, and pop on a List
Python set()
Python Program to Capitalize the First Character of a String
Python Set pop()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python while Loop
Python Program to Find the Largest Among Three Numbers