Steve Wesley Steve Wesley - 2 months ago 8
Python Question

Iteration in one line of code

I am a noob in python and I think I have a relevant question.

I have this two lists in python :

In listA I have the column names of my mysql table.

listA = ["columnA","columnB","columnC"]


In listB I have the result of a query to this values

listB = [["10","30","40"],
["14","28","38"],
["13","23","45"]]


What is the most efficient way in python to produce an output like this?

columnA = 10, columnB = 30, columnC = 40
columnA = 14, columnB = 28, columnC = 38
columnA = 13, columnB = 23, columnC = 45

Answer

A list of dictionaries will work well:

>>> [dict(zip(listA, row)) for row in listB]
[{'columnA': '10', 'columnC': '40', 'columnB': '30'}, {'columnA': '14', 'columnC': '38', 'columnB': '28'}, {'columnA': '13', 'columnC': '45', 'columnB': '23'}]
>>> 
Comments