I am taking example from Mark Lutz book,Learning Python.
keys = ['spam','eggs','toast']
vals=[1,4,7]
D2={}
for (v,k) in zip(keys, vals): D2[k] = v
D2
{1: 'spam', 4: 'eggs', 7: 'toast'}
My example:
D1={}
for (k,v) in zip(keys, vals): D1[k] = v
D1
{'toast': 7, 'eggs': 4, 'spam': 1}
So,I still do not understand indexing,why is for(v,k)?
It is unpacking the key and value from each tuple of the zipped list of the keys and values list, then assigning key/value pairs . The parens are unnecessary for v, k in zip(keys, vals) will also work. The difference between yours and the book's code is the the order of v,k, you use the keys list as keys and the book does it in reverse.
You could also create the dict in one step calling dict on the zipped items, if you reverse the order of the lists passed to zip then you will get the exact same behaviour:
D2 = dict(zip(keys, vals))
print D2
D2 = dict(zip(vals, keys))
print(D2)
{'toast': 7, 'eggs': 4, 'spam': 1}
{1: 'spam', 4: 'eggs', 7: 'toast'}
The only difference is the order. The fact the lists are named keys and values is probably a bit confusing because the values end up being keys and vice versa but the main thing to understand is you are assigning k in your loop to each element from the keys list and the book code is doing the opposite.
zip will return list of tuples:
Demo:
>>> keys = ['spam','eggs','toast']
>>> vals=[1,4,7]
>>> zip(keys, vals)
[('spam', 1), ('eggs', 4), ('toast', 7)]
Unpacking
Demo:
>>> t = (1,2,3)
>>> t
(1, 2, 3)
>>> a,b,c = t
>>> a
1
>>> b
2
>>> c
3
>>> a,b = t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>>
v and second to k.Code:
>>> D2={}
>>> for (v,k) in zip(keys, vals):
... print "v:", v
... print "k", k
... D2[k] = v
... # ^ ^
# Key Value
v: spam
k 1
v: eggs
k 4
v: toast
k 7
>>> D2
{1: 'spam', 4: 'eggs', 7: 'toast'}
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With