1

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}]
Klaus D.
  • 13,874
  • 5
  • 41
  • 48
tins johny
  • 195
  • 1
  • 13

3 Answers3

2
final_list = [{"name": x, "age": y} for x, y in zip(list1, list2)]
Kosuke Sakai
  • 2,336
  • 2
  • 5
  • 12
1
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]})
Ollie
  • 1,641
  • 1
  • 13
  • 31
  • from where can i get list2[i] ? do i need to add a inner loop? – tins johny Oct 30 '19 at 05:07
  • 1
    no, `i` is the index of `list1` _and_ `list2` - it will go from `0` to `2` (for a list of 3 items) - this works because `len(list1) == len(list2)` – Ollie Oct 30 '19 at 05:09
1
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}]

RoyM
  • 735
  • 3
  • 14