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 Dictionary setdefault()
Python max()
Python Set issubset()
Python Program to Parse a String to a Float or Int
Python Program to Iterate Over Dictionaries Using for Loop
Python List extend()
Python Program to Shuffle Deck of Cards
Python Set isdisjoint()
Python Program to Get a Substring of a String
Python callable()
Python isinstance()
Python len()
Python Generators
Python Program to Create Pyramid Patterns
Python Dictionary
Python Set intersection()
Python List count()
Python Tuple
Deep Learning in Python - LazyProgrammer
Python slice()
Python Program to Get File Creation and Modification Date
Python Program to Count the Number of Digits Present In a Number
Python Directory and Files Management
Python RegEx
Python property()
Python String join()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Program to Print Output Without a Newline
Python for Loop
Python Custom Exceptions
Python chr()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman