Convert a list to a dictionary in Python

前端 未结 12 2013
無奈伤痛
無奈伤痛 2020-11-22 04:14

Let\'s say I have a list a in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following o

12条回答
  •  鱼传尺愫
    2020-11-22 04:53

    You can also try this approach save the keys and values in different list and then use dict method

    data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']
    
    keys=[]
    values=[]
    for i,j in enumerate(data):
        if i%2==0:
            keys.append(j)
        else:
            values.append(j)
    
    print(dict(zip(keys,values)))
    

    output:

    {'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}
    

提交回复
热议问题