1

Possible Duplicate:
how to convert two lists into a dictionary (one list is the keys and the other is the values)?

if I have a list of integer:

L=[1,2,3,4]

and I have a list of tuple list:

K=[('a','b'),('c','d'),('e','f'),('g','i')]

how can I make a list of dict where the key is item in K, and the value is integer in L,where each integer is correspond to the item in K

d={('a','b'):1,('c','d'):2,('e','f'):3,('g','i'):4}
Community
  • 1
  • 1
user1805048
  • 63
  • 1
  • 6
  • can I do it with a for loop? I haven't learn zip yet – user1805048 Nov 24 '12 at 06:11
  • See the answers in the duplicate link I posted. One of those does it using a loop. (And explains where the original poster [OP] failed in their attempt at doing it with a loop). The other answer posted there uses `zip` and explains briefly what it does/how it works. – mgilson Nov 24 '12 at 06:16

3 Answers3

5

Use zip() to combine two iterables into pairs, then pass that to the dict constructor:

d = dict(zip(K, L))

Quick demo (take into account that dict does not retain ordering):

>>> L=[1,2,3,4]
>>> K=[('a','b'),('c','d'),('e','f'),('g','i')]
>>> dict(zip(K, L))
{('e', 'f'): 3, ('a', 'b'): 1, ('c', 'd'): 2, ('g', 'i'): 4}

With a for loop and no zip():

d={}
for i, key in enumerate(K):
    d[key] = L[i]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • can I do it with a for loop? I haven't learn zip yet – user1805048 Nov 24 '12 at 06:16
  • @user1805048 -- No better time than now to look up the documentation (which Martijn did for you :) and read it. `zip` is particularly useful. – mgilson Nov 24 '12 at 06:17
  • 2
    @user1805048: Tsk, tsk, cheating on our homework, are we? Easy enough, until you tell me you haven't learned about `enumerate()` yet. Then we'll move on to `range(len(K))` and then have to explain about `range()` too, won't I? – Martijn Pieters Nov 24 '12 at 06:19
0

You should be able to do that with zip:

zipped = zip(K, L)
d = dict(zipped)
sampson-chen
  • 45,805
  • 12
  • 84
  • 81
0

If you NEED to use a for loop (is this your homework?), you can do one starting with:

d = {}
for i in xrange(len(K)):

You should figure out the last line yourself.

Looping over indices is a technique you can use in other languages, and is sometimes (very rarely) necessary in python. In general, you should use python's high-level language features to make your code easier to read easier to read and debug.

krasnerocalypse
  • 966
  • 6
  • 6