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 rstrip()
Python Operator Overloading
Python List reverse()
Python Operators
Python String splitlines()
Python Program to Find the Factors of a Number
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python filter()
Python Program to Check if a Number is Odd or Even
Python hasattr()
Python Program to Remove Punctuations From a String
Python Custom Exceptions
Python max()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Set discard()
Python Set symmetric_difference_update()
Python @property decorator
Python Tuple count()
Python help()
Python Program to Multiply Two Matrices
Python input()
Python staticmethod()
Python Dictionary fromkeys()
Python String strip()
Python Program to Print Hello world!
Python Program to Display Fibonacci Sequence Using Recursion
Python pow()
Python hex()
Python String isalpha()
Python Dictionary update()
Python repr()
APIs in Node.js vs Python - A Comparison