Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a simple list to a dictionary (in python)

Tags:

python

I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it?

list = ['first_key', 'first_value', 'second_key', 'second_value']

Thanks in advance!

like image 295
green69 Avatar asked Apr 20 '26 10:04

green69


2 Answers

The most concise way is

some_list = ['first_key', 'first_value', 'second_key', 'second_value']
d = dict(zip(*[iter(some_list)] * 2))
like image 58
Sven Marnach Avatar answered Apr 23 '26 00:04

Sven Marnach


myDict = dict(zip(myList[::2], myList[1::2]))

Please do not use 'list' as a variable name, as it prevents you from accessing the list() function.

If there is much data involved, we can do it more efficiently using iterator functions:

from itertools import izip, islice
myList = ['first_key', 'first_value', 'second_key', 'second_value']
myDict = dict(izip(islice(myList,0,None,2), islice(myList,1,None,2)))
like image 38
Hugh Bothwell Avatar answered Apr 22 '26 23:04

Hugh Bothwell