Skip to content Skip to sidebar Skip to footer

Python: How To Build A Dict From Plain List Of Keys And Values

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': 2, 'c': 3} What is the natural way to do it in Python?

Solution 1:

>>> x = ["a", 1, "b", 2, "c", 3]
>>> i = iter(x)
>>> dict(zip(i, i))
{'a': 1, 'c': 3, 'b': 2}

Solution 2:

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}

Solution 3:

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}

Solution 4:

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}

Solution 5:

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)}

Post a Comment for "Python: How To Build A Dict From Plain List Of Keys And Values"