'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

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?



Solution 1:[1]

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'}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1