> >>> a
> ['a', 'apple', 'b', 'boy', 'c', 'cat']
> 
> I want to create a dictionary:
>  dict = {'a':'apple',
>          'b':'boy',
>          'c':'cat'}
> 
> 
> Problem:
> How do i capture every alternative element in list a:

>From first principles:

n = 0
while n < len(a):
  keys.append(a[n])
  vals.append(a[n+1])
  n += 2

Or using Python a little more:

tups = []
for n in range(0,len(a),2):  # step 2
   tups.append( (a[n],a[n+1]) )  #list of tuples

d = dict(tups)

Or using it a bit more:

d = dict([(a[n],a[n+1]) for n in range(0,len(a),2)])

For readability's sake I'd use the middle version.

HTH

Alan G.

 



> 
> I am unable to pump the a,b, and c into keys list
> and apple, boy,cat into vals list.
> 
> Trial 1:
> >>> while i >= len(a):
> print a[i]
> i = i+2   -- I thought i+2 will give me alternative
> elements
> 
> Trial 2:
> >>> for index,i in enumerate(range(len(a))):
> print a[i]
> print a[index+1]
> 
> 
> a
> apple
> apple
> b
> b
> boy
> boy
> c
> c
> cat
> cat
> 
> Please help me.  It is also time for me to refer my
> prev. notes  :-(
> 
> thanks
> K
> 
> 
> 
> 
> 
> 
> __________________________________ 
> Do you Yahoo!? 
> Yahoo! Mail - Easier than ever with enhanced search. Learn more.
> http://info.mail.yahoo.com/mail_250
> 
> 
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to