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 list()
Python Dictionary values()
Python Program to Find Armstrong Number in an Interval
Python Program to Split a List Into Evenly Sized Chunks
Python Namespace and Scope
Python Anonymous / Lambda Function
Python String format_map()
Python List remove()
Python Set clear()
Python Program to Swap Two Variables
Python *args and **kwargs
Python Iterators
Python timestamp to datetime and vice-versa
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python slice()
Python Dictionary
Python Program to Print the Fibonacci sequence
Python String translate()
Python RegEx
Python List insert()
Python Type Conversion and Type Casting
Python zip()
Python String maketrans()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Set add()
Python Program to Check If a String Is a Number (Float)
Deep Learning with Python - Francois Chollet
Python Set copy()
Python Program to Get the Class Name of an Instance
Python Program to Return Multiple Values From a Function
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty