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 del Statement
Python int()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python strftime()
Python Program to Check if a Number is Odd or Even
Python String index()
Python Program to Find Armstrong Number in an Interval
Python Program to Print all Prime Numbers in an Interval
Python Program to Check If Two Strings are Anagram
Python Data Types
Python Program to Count the Occurrence of an Item in a List
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python round()
Python Program to Create Pyramid Patterns
Python String title()
Python String rjust()
Python String splitlines()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python object()
Python Program to Check Armstrong Number
Python Program to Convert String to Datetime
Python Program to Safely Create a Nested Directory
Python Operator Overloading
Python super()
Python Program to Print Colored Text to the Terminal
Python List index()
Python String rstrip()
Python Program to Find Factorial of Number Using Recursion
Python Program to Remove Duplicate Element From a List
Python String isalnum()
Python set()
Python Program to Return Multiple Values From a Function