x = ['1', '2', '3', '4']
y = [[1,0],[2,0],[3,0],[4,]]
I want to create a dictionary so the x and y values would correspond like this:
1: [1,0], 2: [2,0]
and etc
x = ['1', '2', '3', '4']
y = [[1,0],[2,0],[3,0],[4,]]
I want to create a dictionary so the x and y values would correspond like this:
1: [1,0], 2: [2,0]
and etc
You can use zip function:
dict(zip(x, y))
>>> x = ['1', '2', '3', '4']
... y = [[1,0],[2,0],[3,0],[4,]]
>>> dict(zip(x, y))
0: {'1': [1, 0], '2': [2, 0], '3': [3, 0], '4': [4]}
In python > 2.7 you can use dict comprehension:
>>> x = ['1', '2', '3', '4']
>>> y = [[1,0],[2,0],[3,0],[4,]]
>>> mydict = {key:value for key, value in zip(x,y)}
>>> mydict
{'1': [1, 0], '3': [3, 0], '2': [2, 0], '4': [4]}
>>>
Still the best answer has already been given
dict(zip(x, y))
In python <= 2.7 you can use itertools.izip
in case you work with big lists as izip
returns an iterator. For small lists like yours, the use of izip
would be overkilling. Note however that itertools.izip
dissapeared in python 3. In python 3, the zip
builtin already returns an iterator and in consequence izip
was not needed anymore.
The quick and easy answer is dict(zip(x,y))
, if you're ok with the keys being strings. otherwise, use dict(zip(map(int,x),y))
You can use itertools.izip
to accomplish this.
from itertools import izip
x = ['1', '2', '3', '4']
y = [[1,0],[2,0],[3,0],[4,]]
dict(izip(x, y))
If your flavor of Python is 3.x, then you can use itertools.zip_longest
to do the same thing.
from itertools import zip_longest
x = ['1', '2', '3', '4']
y = [[1,0],[2,0],[3,0],[4,]]
dict(zip_longest(x, y))