[英]How to turn an existing list into a key-value pair for a dictionary in Python?
[英]Getting issue while trying to convert a list to a dictionary in python but it's extracting only the last key-value pair from the list
我的清單看起來像這樣,
[' Objective ',
' To get an opportunity where I can make the best of my potential.',
' Experience ',
' Division of Cranes Software International Ltd . Project title November-2021 • Each Differentiation using Iris Flower UNDERGRADUATE PROJECT']
ps列表的長度是101
我正在嘗試將此列表轉換為字典
col_dict = {}
for i in range(1, len(columns_lst),2):
col_dict = {columns_lst[i] : columns_lst[i+1]}
col_dict[columns_lst[i]] = columns_lst[i + 1]
但它只存儲col_dict
中的最后一個鍵和值對,而不是列表的全部數據。 請幫助我了解為什么會發生這種情況以及如何解決?
您在每次迭代中定義一個全新的字典。 消除
col_dict = {columns_lst[i] : columns_lst[i+1]}
此外,由於您正在迭代列表的長度並向前看, i
可以采用的最后一個索引是len(columns_lst)-2
因為最后一個索引是len(columns_lst)-1
( i+1
采用)。 所以你的代碼應該是
for i in range(0, len(columns_lst)-1, 2):
col_dict[columns_lst[i]] = columns_lst[i + 1]
另一種方法是使用zip
以便您可以將偶數索引處的項目和奇數索引處的項目放在一起:
col_dict = {i:j for i, j in zip(columns_lst[::2], columns_lst[1::2])}
Output:
{' Objective ': ' To get an opportunity where I can make the best of my potential.',
' Experience ': ' Division of Cranes Software International Ltd . Project title November-2021 • Each Differentiation using Iris Flower UNDERGRADUATE PROJECT'}
實現 output 的另一種簡單方法是:
# l = [' Objective ', ' To get... ]
out = {l[2*i]: l[2*i+1] for i in range(len(l)//2)}
# or
# out = {l[i]: l[i+1] for i in range(0, len(l), 2)}
或者在 python ≥ 3.10 上,使用itertools.pairwise
:
from itertools import pairwise
out = dict(pairwise(l))
output:
{' Objective ': ' To get an opportunity where I can make the best of my potential.',
' Experience ': ' Division of Cranes Software International Ltd . Project title November-2021 • Each Differentiation using Iris Flower UNDERGRADUATE PROJECT'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.