[英]python list of tuples to list of dicts for use by csv.dictwriter
我有這種情況
x=['a','b','c'] #Header
y=[(1,2,3),(4,5,6)] #data
我需要創建以下結構
[{'a':1, 'b':2, 'c':3}, {'a':4, 'b':5, 'c':6}]
任何更好的方法(例如python專家)
rows=[]
for row in range(0,len(y)):
rec={}
for col in range(0, len(x)):
rec[x[col]]=y[row][col]
rows.append(rec)
print(rows)
上面的代碼將提供理想的結果,但是我正在尋找一種像下面這樣的解決方案
rows=list( ( {x[col]:y[row][col]} for row in range(0,len(y)) for col in range(0, len(x)) ) )
輸出:
[{'a': 1}, {'b': 2}, {'c': 3}, {'a': 4}, {'b': 5}, {'c': 6}]
但這將列表作為單個詞典而不是組合詞典。 有任何想法嗎???
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.