Table of Contents
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
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
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