-6

How to Turn lists in to list of dict?

From:

name=['Mary','Susan','John']
age=[15,30,20]
sex=['F','F','M']

I want to have :

mylist= [ {'name':'Mary','age':15,'sex':'F'},
          {'name':'Susan','age':30,'sex':'F'},
          {'name':'John','age':20,'sex':'M'},
          ]
  • 1
    You should look into Pandas – avloss Jul 14 '20 at 03:58
  • 4
    Take a look at `zip` – Chris Jul 14 '20 at 03:59
  • 4
    Have you tried any thing so far ? – sushanth Jul 14 '20 at 03:59
  • 1
    If you put your labels in a list, `keys = ['name', 'age', 'sex']`, and `zip` your data lists, `t = zip(name, age, sex)`, you can use [this solution](https://stackoverflow.com/a/35763623/4518341) on "Convert list of lists to list of dictionaries". See also [Convert two lists into a dictionary](https://stackoverflow.com/q/209840/4518341) – wjandrea Jul 14 '20 at 04:04
  • Does this answer your question? [Convert two lists into a dictionary](https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary) – Gino Mempin Jul 14 '20 at 05:06

3 Answers3

3

This is a perfect example of the zip function. https://docs.python.org/3.8/library/functions.html#zip

Given:

name = ['Mary','Susan','John']
age = [15,30,20]
sex = ['F','F','M']

Then:

output = []
for item in zip(name, age, sex):
  output.append({'name': item[0], 'age': item[1], 'sex': item[2]})

Will produce:

[
  {'name': 'Mary', 'age': 15, 'sex': 'F'}, 
  {'name': 'Susan', 'age': 30, 'sex': 'F'}, 
  {'name': 'John', 'age': 20, 'sex': 'M'},
]

There is an even shorter way to do it with list comprehensions:

output = [{'name': t[0], 'age': t[1], 'sex': t[2]} for t in zip(name, age, sex)]
gahooa
  • 131,293
  • 12
  • 98
  • 101
0

Here is an example one:

def Convert(a): 
    it = iter(lst) 
    res_dct = dict(zip(it, it)) 
    return res_dct 
      
# Driver code 
lst = ['a', 1, 'b', 2, 'c', 3]  
print(Convert(lst)) 

You can use this for your code.

UdayanS
  • 47
  • 1
  • 8
0

The easiest way to go about it would be something like this:

name=['Mary','Susan','John']
age=[15,30,20]
sex=['F','F','M']
list_dict = []
for i in range(0, len(name)):
    dict_temp = {}
    dict_temp['name'] = name[i]
    dict_temp['age'] = age[i]
    dict_temp['sex'] = sex[i]
    list_dict.append(dict_temp)

I am assuming length of all lists are same.