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 Get Line Count of a File
Python Tuple count()
Python if...else Statement
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Print Output Without a Newline
Python List pop()
Python input()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python datetime
Python Program to Check Armstrong Number
Python frozenset()
Python callable()
Python String casefold()
Python Machine Learning - Sebastian Raschka
Python Global, Local and Nonlocal variables
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Print the Fibonacci sequence
Python Program to Convert Kilometers to Miles
Python Iterators
Python ascii()
Python String isdecimal()
Python Program to Create a Countdown Timer
Python String islower()
Python Program to Calculate the Area of a Triangle
Python String partition()
Python iter()
Python Set intersection_update()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Deep Learning with Applications Using Python - Navin Kumar Manaswi