How to convert a list into a dictionary in python?

徘徊边缘 提交于 2021-02-05 12:31:45

问题


I have a list of objects:

['fb_ads_sm', 'Active', '18 hr ago', '23', 'sm_sg13', 'Pending', '12 hr ago', '0', ...]

How do I convert this into a dictionary where the keys are the 1st and 5th elements and the values are the 2nd and 6th elements?

dictionary = {'fb_ads_sm': 'Active', 'sm_sg13': 'Pending', ...}

回答1:


You can try to use dict comprehension with list slicing

a = ['fb_ads_sm', 'Active', '18 hr ago', '23', 'sm_sg13', 'Pending', '12 hr ago']
{k: v for k, v in zip(a[::4], a[1::4])}

OR

dict(zip(a[::4], a[1::4]))

Output

{'fb_ads_sm': 'Active', 'sm_sg13': 'Pending'}



回答2:


def Convert(a): 
    it = iter(lst) 
    res_dct = dict(zip(it, it)) 
    return res_dct 
           
lst = ['fb_ads_sm', 'Active', '18 hr ago', '23', 'sm_sg13', 'Pending', '12 hr ago'] 
print(Convert(lst))



回答3:


Try this method: data is your actual list.

dict_list = {}
for i in range(0, len(data)-1, 4):
    dict_list[data[i]] = data[i+1]


来源:https://stackoverflow.com/questions/62872148/how-to-convert-a-list-into-a-dictionary-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!