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:
Deep Learning in Python - LazyProgrammer
Python Program to Display the multiplication Table
APIs in Node.js vs Python - A Comparison
Python Program to Generate a Random Number
Python String isalnum()
Python type()
Python Program to Get the Class Name of an Instance
Python Get Current time
Python Global, Local and Nonlocal variables
Python Program to Create a Countdown Timer
Python List pop()
Python bool()
Python vars()
Python __import__()
Python String split()
Python dir()
Python hasattr()
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Check Armstrong Number
Python Program to Count the Number of Occurrence of a Character in String
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Dictionary popitem()
Python globals()
Python String partition()
Python Program to Check if a Key is Already Present in a Dictionary
Python zip()
Python String islower()
Python String join()
Python Program to Find the Size (Resolution) of a Image
Python Program to Print the Fibonacci sequence
Python Set clear()
Python Operator Overloading