;

Python Program to Map two lists into a Dictionary


Tutorialsrack 08/05/2020 Python

In this python program, we will learn how to map two lists into a dictionary. In this program, we use the python built-in zip() and dict() functions. The zip() is a Python built-in function and this function is used to Make an iterator that aggregates elements from each of the iterables. And The dict() is a Python built-in function and this function returns a dictionary object or simply creates a dictionary in Python.

Here is the source code of the program to map two lists into a dictionary.

Program 1: Python Program to Map two lists into a Dictionary Using zip() function

Python Program to Map two lists into a Dictionary Using zip() function
# Python Program to Map two lists into a Dictionary Using zip() function

# Declare the Dictionaries
keys_list = ['Name', 'Age', 'Designation']
values_list = ['John', 25, 'Developer']

# Print the Original List
print("Key List",keys_list)
print("Value List", values_list)

myDict = {k: v for k, v in zip(keys_list, values_list)}

# Print the Dictionary
print("\nDictionary Items:  ",  myDict)
Output

Key List ['Name', 'Age', 'Designation']

Value List ['John', 25, 'Developer']

 

Dictionary Items:   {'Name': 'John', 'Age': 25, 'Designation': 'Developer'}

Program 2: Another approach to insert lists into a Dictionary using zip() function

Another approach to insert lists into a Dictionary using zip() function
# Another approach to insert lists into a Dictionary using zip() function

# Declare the Dictionaries
keys = ['name', 'age', 'job']
values = ['John', 25, 'Developer']

# Print the Original List
print("Key List",keys_list)
print("Value List", values_list)

myDict = dict(zip(keys, values))

# Print the Dictionary
print("\nDictionary Items  :  ",  myDict)
Output

Key List ['Name', 'Age', 'Designation']

Value List ['John', 25, 'Developer']

 

Dictionary Items  :   {'name': 'John', 'age': 25, 'job': 'Developer'}


Related Posts



Comments

Recent Posts
Tags