Creating dictionary from list in Python with first item in list as header

  • A+
Category:Languages

I am trying to create a list of dictionary with the lists below.

a = [["Name","Mary","Tom","John"],["Age","21","23","12"],["Gender","F","M","M"]] 

I would like the output to be:

a_list=[{"Name":"Mary", "Age":"21", "Gender":"F"},{"Name":"Tom", "Age":"23", "Gender":"M"},{"Name":"John", "Age":"12", "Gender":"M"}] 

I tried to use zip but could not get it to work. Please help!

 


First we can pull the header entries out so we're left with just the values:

headers, values = zip(*((x[0], x[1:]) for x in a)) print(headers, values) # ('Name', 'Age', 'Gender') (['Mary', 'Tom', 'John'], ['21', '23', '12'], ['F', 'M', 'M']) 

Then we can zip together the values, then zip each of those triples with headers to form the dictionaries:

print([dict(zip(headers, triple)) for triple in zip(*values)]) # [{'Name': 'Mary', 'Age': '21', 'Gender': 'F'}, {'Name': 'Tom', 'Age': '23', 'Gender': 'M'}, {'Name': 'John', 'Age': '12', 'Gender': 'M'}] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: