> I have a simple list:
> ['a', 'apple', 'b', 'boy', 'c', 'cat']
> I want to create a dictionary:
> dict = {'a':'apple', 'b':'boy', 'c':'cat'}

From the Quick and Dirty Department: If you have Python version 2.3 or later, you can use 'itertools' to unflatten the list in a very concise manner. Here is an interpreter session using your example data above.

>>> l = ['a', 'apple', 'b', 'boy', 'c', 'cat']
>>> d = {}
>>> import itertools
>>> slice0 = itertools.islice(l,0,None,2)
>>> slice1 = itertools.islice(l,1,None,2)
>>> while True:
...     try:
...         d[slice0.next()] = slice1.next()
...     except: StopIteration
...         break
...  
>>> d
{'a': 'apple', 'c': 'cat', 'b': 'boy'}

This should be fairly space-efficient. As another approach, you could use extended slicing to break the list apart (creating two new lists could be expensive) and then patch it back together again:

>>> slice0 = l[::2]
>>> slice1 = l[1::2]
>>> slice0
['a', 'b', 'c']
>>> slice1
['apple', 'boy', 'cat']
>>> d = dict(zip(slice0,slice1))
>>> d
{'a': 'apple', 'c': 'cat', 'b': 'boy'}
>>>

In both cases, we get slice0 by starting at position 0 in the list and taking every other item and we get get slice1 by starting at position 1 in the list and again taking every other item.

Hope this helps!


Do you Yahoo!?
Yahoo! Mail - Helps protect you from nasty viruses.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to