3

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)?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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
>>> 

  1. We Iterate on list, so its unpacking first item from tuple to v and second to k.
  2. Create new key and value pair in the D2 dictionary.

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'}
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.