Python: how to build a dict from plain list of keys and values

后端 未结 5 1440
耶瑟儿~
耶瑟儿~ 2020-12-06 01:22

I have a list of values like:

[\"a\", 1, \"b\", 2, \"c\", 3]

and I would like to build such a dict from it:

{\"a\": 1, \"b\         


        
相关标签:
5条回答
  • 2020-12-06 01:51

    I don't really see many situations where you would run into this exact problem, so there is no 'natural' solution. A quick one liner that should do the trick for you would be however:

       {input_list[2*i]:input_list[2*i+1] for i in range(len(input_list)//2)}
    
    0 讨论(0)
  • 2020-12-06 01:52
    >>> x = ["a", 1, "b", 2, "c", 3]
    >>> i = iter(x)
    >>> dict(zip(i, i))
    {'a': 1, 'c': 3, 'b': 2}
    
    0 讨论(0)
  • 2020-12-06 01:55

    You can zip the lists of alternate elements like so

    >>> lst = ["a", 1, "b", 2, "c", 3]
    >>> dict(zip(lst[::2], lst[1::2])
    {'a': 1, 'c': 3, 'b': 2}
    
    0 讨论(0)
  • 2020-12-06 02:00

    This seems rather succint, but I wouldn't call it very natural:

    >>> l = ["a", 1, "b", 2, "c", 3]
    >>> dict(zip(l[::2], l[1::2]))
    {'a': 1, 'c': 3, 'b': 2}
    
    0 讨论(0)
  • 2020-12-06 02:09

    Another way:

    >>> l = ["a", 1, "b", 2, "c", 3]
    >>> dict([l[i:i+2] for i in range(0,len(l),2)])
    {'a': 1, 'c': 3, 'b': 2}
    
    0 讨论(0)
提交回复
热议问题