我想從多個串列創建一個字典
list_countries=['italy','france']
list_leagues=[['serie-a','serie-b'], 'ligue-1']
keys=['Country','League']
values=[list_countries,list_leagues]
spam = [dict(zip(keys, item)) for item in zip(*values)]
print(spam)
輸出
[{'Country': 'italy', 'League': ['serie-a', 'serie-b']},
{'Country': 'france', 'League': 'ligue-1'}]
預期輸出
[{'Country': 'italy', 'League': 'serie-a'},
{'Country': 'italy','League': 'serie-b'},
{'Country': 'france', 'League': 'ligue-1'}]
uj5u.com熱心網友回復:
像這樣的東西
list_countries=['italy','france']
list_leagues=[['serie-a','serie-b'], 'ligue-1']
data = []
for c,l in zip(list_countries,list_leagues):
if isinstance(l,list):
for ll in l:
data.append({'Country':c,'League':ll})
else:
data.append({'Country':c,'League':l})
print(data)
輸出
[{'Country': 'italy', 'League': 'serie-a'}, {'Country': 'italy', 'League': 'serie-b'}, {'Country': 'france', 'League': 'ligue-1'}]
uj5u.com熱心網友回復:
如果你想使用串列理解:
spam = [dict(zip(keys, [a,c])) for a,b in zip(*values)
for c in (b if isinstance(b,list) else [b])]
輸出:
[{'Country': 'italy', 'League': 'serie-a'},
{'Country': 'italy', 'League': 'serie-b'},
{'Country': 'france', 'League': 'ligue-1'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358196.html
