My list look something like this,
[' 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']
P.s. the length of list is 101
And I'm trying to convert this list to a dict
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]
But it's storing only the last key and value pair in col_dict and not the whole data of the list. Please help me understand why is this happening and how to resolved it?
CodePudding user response:
You're defining a brand new dictionary in every iteration. Remove
col_dict = {columns_lst[i] : columns_lst[i 1]}
Also since you're iterating over the length of the list and looking forward, the last index i can take is len(columns_lst)-2 since the last index is len(columns_lst)-1 (which i 1 takes). So your code should be
for i in range(0, len(columns_lst)-1, 2):
col_dict[columns_lst[i]] = columns_lst[i 1]
Another way is to use zip so that you can walk the items at even numbered indexes and items at odd-numbered indexes together:
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'}
CodePudding user response:
Another simple way to achieve the output is:
# 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)}
Or on python ≥ 3.10, use 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'}
