GoCoding.org

Program to construct a dictionary from the list using Python

by | Mar 13, 2021 | Python Programs

Introduction

In this section of python programming, we will learn to construct a dictionary from the given list with key as the concatenation of key + {list element}.

Program to construct a dictionary from the list

Program

input_list = [ "Ford", "Aston Martin", "McLaren Senna", "Bently"]
input_key = "car_"
#Using Dictionary Comprehension
result = { input_key + str(i) : i for i in input_list }
print("Dictonary created using dictionary comprehension is:",str(result))


#Using loop
res = dict()
for i in input_list:
    res[input_key + str(i)] = i
print("Dictornary created using loop is:", str(res))

 

Output

Program to construct a dictionary from the list Output

Explanation

In the above python code, we have used dictionary comprehension and loop to construct a dictionary from the list.

The dictionary comprehension will pair up the key (concatenate key + list element) and list element and returns the new dictionary.

Similarly in loop, we have traversed each element in the list and for each key ( concatenate key + list element) there is assigned the corresponding list element. When all the elements are traversed and stored as key-value pair in the dictionary, the new dictionary is printed on the screen.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.