0

In python how would you iterate through a list (column names) and a list of tuples (row values) in order to build a list of dictionaries? The keys always being generated from the first array and the values generated from each tuple?

col = ['id', 'username', 'email']
rows = [('1234', 'first', 'first@email.com'), ('5678', 'second', 'second@email.com')]

result = [{'id':'1234', 'username':'first', 'email':'first@email.com'},{'id':'5678', 'username':'second', 'email':'second@email.com'}]
Alec
  • 8,529
  • 8
  • 37
  • 63
ckingchris
  • 559
  • 1
  • 12
  • 25

4 Answers4

1

You can do it like this:

col = ['id', 'username', 'email']
rows = [('1234', 'first', 'first@email.com'), ('5678', 'second', 'second@email.com')]

result = [dict(zip(col, i)) for i in rows]

gives

[{'id': '1234', 'username': 'first', 'email': 'first@email.com'}, {'id': '5678', 'username': 'second', 'email': 'second@email.com'}]
Jarvis
  • 8,494
  • 3
  • 27
  • 58
1

Here's one way:

[dict(zip(col, row)) for row in rows]

How this works:

  • The [... for row in rows] part loops through the rows list to construct a new list.
  • zip(col, row) matches up corresponding items of col and row, so we end up with [('id', '1234'), ('username', 'first'), ...]
  • Finally, dict(...) converts the list of tuples into a dictionary.
Jiří Baum
  • 6,697
  • 2
  • 17
  • 17
1

You can use the zip() function:

[in]: 
col = ['id', 'username', 'email']
rows = [('1234', 'first', 'first@email.com'), ('5678', 'second', 'second@email.com')]
result = [dict(zip(col, r)) for r in rows]


[out]: 
[{'id': '1234', 'username': 'first', 'email': 'first@email.com'}, {'id': '5678', 'username': 'second', 'email': 'second@email.com'}]
Alec
  • 8,529
  • 8
  • 37
  • 63
0

I guess this is what you expecting:

result = []
for i,rowsv in enumerate(rows):
  row_num=0
  for colv in col:
    if(row_num==0):
      result.append("{"+colv+":"+rowsv[row_num])
    elif(row_num== len(col)-1):
      result.append(colv+":"+rowsv[row_num]+"}")
    else:
      result.append(colv+":"+rowsv[row_num])
    row_num+=1
print(result)

output:

['{id:1234', 'username:first', 'email:first@email.com}', '{id:5678', 'username:second', 'email:second@email.com}']
chethan
  • 115
  • 10