How to convert a list into a dictionary in python?

后端 未结 3 2024
说谎
说谎 2021-01-29 14:33

I have a list of objects:

[\'fb_ads_sm\', \'Active\', \'18 hr ago\', \'23\', \'sm_sg13\', \'Pending\', \'12 hr         


        
相关标签:
3条回答
  • 2021-01-29 15:14
    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))
    
    0 讨论(0)
  • 2021-01-29 15:23

    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]
    
    0 讨论(0)
  • 2021-01-29 15:34

    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'}
    
    0 讨论(0)
提交回复
热议问题