Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

How to iterate through an array and a list of tuples making a list of dictionaries in Python?

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', '[email protected]'), ('5678', 'second', '[email protected]')]

result = [{'id':'1234', 'username':'first', 'email':'[email protected]'},{'id':'5678', 'username':'second', 'email':'[email protected]'}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...