Help with creating a dict from list and range

Steve Holden steve at holdenweb.com
Fri Oct 14 11:37:59 EDT 2005


Echo wrote:
> Hello,
> Here is what I am trying to do. I am trying to make a dict that has a 
> key that is the value an element in a list and the value for the dict to 
> be the index.
> This is the closest I have been able to get:
>  dict((d[0],i) for d in self.cu.description for i in 
> xrange(len(self.cu.description)-1))
> 
> That however does not work. the value for all the dict is 40. Not 1, 2, 
> 3, ... that I was hoping for.
> 
> Am I even close at creating the dict that I want? Is there a better way 
> to go about it?
> 
 >>> description = ["first", "second", "third"]
 >>> for x in enumerate(description):
...   print x
...
(0, 'first')
(1, 'second')
(2, 'third')
 >>> dct = dict((x[1], x[0]) for x in enumerate(description))
 >>> dct
{'second': 1, 'third': 2, 'first': 0}

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list