Convert a list to a dictionary in Python

前端 未结 12 2133
無奈伤痛
無奈伤痛 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:10

    Simple answer

    Another option (courtesy of Alex Martelli - source):

    dict(x[i:i+2] for i in range(0, len(x), 2))
    

    Related note

    If you have this:

    a = ['bi','double','duo','two']
    

    and you want this (each element of the list keying a given value (2 in this case)):

    {'bi':2,'double':2,'duo':2,'two':2}
    

    you can use:

    >>> dict((k,2) for k in a)
    {'double': 2, 'bi': 2, 'two': 2, 'duo': 2}
    

提交回复
热议问题