Python for Indexing Loops

I'm taking an example from Mark Lutz's Learning Python book.

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 don't understand indexing, why for (v, k)?

+3


source to share


2 answers


It is unpacking the key and value from each set of zipped list of keys and values, then assigning the key / value pairs. No paranas for v, k in zip(keys, vals)

will also work. The difference between your code and the book code is the order v,k

, you use the list keys

as keys and the book does it in reverse order.

You can also create a dict in one step by calling the dict on zipped items, if you change the order of the lists passed in zip then you get the same behavior:



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 order. The fact that lists are called keys and values ​​is probably a little confusing because values ​​are ultimately keys and vice versa, but the main thing to understand is that you are assigning k

each item from the list in your loop keys

and the book code does the opposite.

+6


source


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

      


  • We iterate through the list, so its unboxing the first element from the tuple to v

    and the second value k

    .
  • Create a new key and value pair in dictionary D2.

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

      

+4


source







All Articles