You may use zip
to create tuples
of key-value pairs and then type-cast these to dict
as:
>>> my_list = ['sam', '25', 'matt', '30', 'jack', '27']
>>> dict(zip(my_list[::2], my_list[1::2]))
{'matt': '30', 'jack': '27', 'sam': '25'}
Or you may use a dictionary comprehension with range
as:
>>> {my_list[i]: my_list[i+1] for i in range(0, len(my_list), 2)}
{'matt': '30', 'jack': '27', 'sam': '25'}
Performance comparison of both the solutions:
# Using `zip`
mquadri$ python -m timeit -s "my_list = ['sam', '25', 'matt', '30', 'jack', '27']" "{my_list[i]: my_list[i+1] for i in range(0, len(my_list), 2)}"
1000000 loops, best of 3: 0.872 usec per loop
# Using "dictionary comprehension"
mquadri$ python -m timeit -s "my_list = ['sam', '25', 'matt', '30', 'jack', '27']" "dict(zip(my_list[::2], my_list[1::2]))"
1000000 loops, best of 3: 1.53 usec per loop