我需要有關元組串列的幫助。
我有下一個串列:
list = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]
我需要將元組轉換為字典并獲得下一個結果:
list = [{'name':'x1', 'amount':'10'}, {'name':'x2', 'amount':'15'},
{'name':'x3', 'amount':'35'}, {'name':'x4', 'amount':'55'}]
uj5u.com熱心網友回復:
您還可以dict()在串列理解中使用建構式:
out = [dict(zip(['name','amount'], tpl)) for tpl in lst]
或者等效地,您也可以dict()在內部使用建構式map:
out = list(map(lambda tpl: dict(zip(['name','amount'], tpl)), lst))
輸出:
[{'name': 'x1', 'amount': '10'},
{'name': 'x2', 'amount': '15'},
{'name': 'x3', 'amount': '35'},
{'name': 'x4', 'amount': '55'}]
uj5u.com熱心網友回復:
嘗試嵌套字典理解。
list_of_tuples = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]
result = [{'name': name, 'amount': amount} for name, amount in list_of_tuples]
這相當于更冗長(但可能更易讀)
result = []
for name, amount in list_of_tuples:
d = {'name': name, 'amount': amount}
result.append(d)
uj5u.com熱心網友回復:
list = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]
_list = []
for i in list:
_list.append({"name":i[0],"amount":i[1]})
print(_list)
uj5u.com熱心網友回復:
你可以這樣做:
list = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]
dic={}
list2=[]
for i in range(len(list)):
dic2={}
dic2['name']=list[i][0]
dic2['amount']=list[i][1]
list2.append(dic2)
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400144.html
上一篇:字典物件沒有屬性拆分
