1
因此,我正在嘗試構建字典,其中鍵是列表的第一個元素,其餘元素是值,因此它具有以下內容格式: {str:[str,str,str,int,str]}但現在我不明白如何從列表中獲取第一個元素作爲鍵,其餘爲值。 下面是一個例子:如何從列表中獲取鍵和值以添加到字典
這是列表
['asmith', 'Alice', 'Smith', '31', 'F', '[email protected]']
第一個元素[0]鍵,其餘的價值
這是我到目前爲止有:
def create_dict(my_file):
information = my_file.read()
information = information.split()
res = []
for element in information:
res.append(element)
print(res)
print(res[0])
d = dict((res[0], res[1:6]) for res[0] in res[1:6])
print(d)
這個越來越其輸出IM是不正確:{'S':'mith','F':'','A':'蝨子','3':'1','a':'蝨子。'} –
您需要提供MCVE的輸入數據。看起來你並沒有注意到我在回答中提到的警告(「假設'res'是列表清單」)。如果'res'是一個* single *列表(不是列表的嵌套列表),那麼是的解決方案是不一樣的。 –
否則,如果您的列表僅代表一個*單個*人,似乎毫無意義/多餘/不必要將此代碼轉換爲字典。請在你的問題中顯示「信息」的一些示例數據。 –