How to make list of dictionary from two list in python

I need to make a list of dictionary from two list. keys of the dictionary is are fixed.

list1 = ['a','b','c']

list2 = [1,2,3]

i need to create a list of dictionary like this,

final_list = [{'name':'a','age':1},{'name':'b','age':2},{'name':'c','age':3}]

final_list = [{"name": x, "age": y} for x, y in zip(list1, list2)]

The basic method that can be applied to perform this task is the brute force method to achieve this. For this, simply declare a dictionary, and then run nested loop for both the lists and assign key and value pairs to from list values to dictionary.

list1 = ['a','b','c']
list2 = [1,2,3]

final_list = []

for i in range(len(list1)):
    final_list.append({'name': list1[i], 'age': list2[i]})

In Python 2, zip returns a list, to avoid creating an unnecessary list, use izip instead (aliased to zip can reduce code changes when you move to Python 3). from itertools import izip as zip So that is still (2.7):

final_list = [{'name':x, 'age':y} for (x,y) in zip(list1, list2)]

Out: [{'name': 'a', 'age': 1}, {'name': 'b', 'age': 2}, {'name': 'c', 'age': 3}]

How to convert two lists to dictionary. Let’s say we have two lists. lstStr = ['millie', 'caleb', 'finn', 'sadie', 'noah'] lstInt = [11, 21, 19, 29, 46] We will take the first list as the keys for the dictionary and the second list as values. To achieve that and create a dictionary from two lists, we can use Python zip() function.

Python Program to insert two lists into a Dictionary Example 2. This Python code is another approach to insert lists into a Dictionary. In this program, we are using a dict keyword along with zip function. # Python Program to Map two lists into a Dictionary keys = ['name', 'age', 'job'] values = ['John', 25, 'Developer'] myDict = dict (zip (keys, values)) print ("Dictionary Items : ", myDict)

Converting a list to dictionary with list elements as keys in dictionary. using dict.fromkeys () '''. dictOfWords = dict.fromkeys(listOfStr , 1) dict.fromKeys () accepts a list and default value. It returns a dictionary with items in list as keys. All dictionary items will have same value, that was passed in fromkeys ().

Converting a list of lists to a dictionary can be useful in certain situations. We can think of a Python list of lists as a database table where the outer list represent the table and the inner lists represent the rows. A database table has a primary key and the rest of the fields hold the data.