how to convert two lists into a dictionary (one list is the keys and the other is the values)?
python
Solution
I think something like:
dik = dict(zip(dato,otro))
is a little cleaner...
If `dik` already exists and you're just updating it:
dik.update(zip(dato,otro))
If you don't know about `zip`, you should invest a little time learning it. It's super useful.
a = [ 1 , 2 , 3 , 4 ]
b = ['a','b','c','d']
zip(a,b) #=> [(1,'a'),(2,'b'),(3,'c'),(4,'d')] #(This is actually a zip-object on python 3.x)
`zip` can also take more arguments (`zip(a,b,c)`) for example will give you a list of 3-tuples, but that's not terribly important for the discussion here.
This happens to be exactly one of the things that the `dict` "constructor" (type) likes to initialize a set of `key-value` pairs. The first element in each `tuple` is the `key` and the second element is the `value`.
Problem
This is code in IDLE2 in python, and error. I need to include each "data" element as key and value "otro", in an orderly manner. Well "data" and "otro" it's list with 38 string's, as for "dik" it's an dictionary. ``` >>> for i in range(len(otro)+1): dik[dato[i]] = otro[i] Traceback (most recent call last): File "<pyshell#206>", line 2, in <module> dik[dato[i]] = otro[i] IndexError: list index out of range >>> ``` this problem is range(0, 38) output -> (0, 1,2,3 ... 37) and it is all messy