Convert a list to a dictionary in Python

前端 未结 12 2132
無奈伤痛
無奈伤痛 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 05:06

    You can use a dict comprehension for this pretty easily:

    a = ['hello','world','1','2']
    
    my_dict = {item : a[index+1] for index, item in enumerate(a) if index % 2 == 0}
    

    This is equivalent to the for loop below:

    my_dict = {}
    for index, item in enumerate(a):
        if index % 2 == 0:
            my_dict[item] = a[index+1]
    

提交回复
热议问题