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 Find the Largest Among Three Numbers
APIs in Node.js vs Python - A Comparison
Python String partition()
Python Anonymous / Lambda Function
Python Program to Print Colored Text to the Terminal
Python Function Arguments
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Strings
Python Program to Check Prime Number
Python Program to Generate a Random Number
Python Dictionary clear()
Python print()
Python Recursion
Python map()
Python pass statement
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python zip()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python set()
Deep Learning with Python - Francois Cholletf
Python Set add()
Python String lstrip()
Python Functions
Python Program to Compute the Power of a Number
Python Set clear()
Python reversed()
Python Set discard()
Python String lower()
Python Package
Python String casefold()
Python tuple()
Python Dictionary keys()