[英]how to get keys and values from a list to add to dictionary
因此,我嘗試構建一個字典,其中的鍵是列表的第一個元素,其余的元素是值,因此它具有以下格式:{str:[str,str,str,int,str] },但現在我還不了解如何從列表中獲取第一個元素作為鍵,其余如何獲取值。 這是一個例子:
這是清單
['asmith', 'Alice', 'Smith', '31', 'F', 'alice.smith@example.com']
第一個元素[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)
您的理解在這里很混亂:
d = dict((res[0], res[1:6]) for res[0] in res[1:6])
您可能會在循環中執行以下操作,假設res
是列表列表:
d = {}
for r in res:
d[r[0]] = r[1:6]
或使用理解:
d = {r[0]:r[1:6] for r in res}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.