[Tutor] How to create a key-value pairs with alternative elements in a list ... please help.

Scott Widney swidneylv at yahoo.com
Wed Jan 12 23:39:41 CET 2005


> 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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050112/13a71a6a/attachment.html


More information about the Tutor mailing list