![]() |
Available news archives:
comp.lang.tcl
-
comp.lang.python
-
comp.security.firewalls
-
sci.crypt -
comp.lang.php -
comp.lang.javascript
|
|
comp.lang.python archiveRe: Splitting string into dictionary
From: Terry Hancock <hancock@anansispaceworks.com>
Date: Fri Jul 01 2005 - 11:38:51 CEST
On Friday 01 July 2005 12:35 am, David Pratt wrote:
Try it out in the interpreter:
Test data:
Splitting, you already know:
The list comprehension generates a new list based on the old one,
>>> translations = [x.strip(" '") for x in line.split('|')]
Then Robert did some real magic by using extended slice notation:
>>> translations[::2]
(count from 0, every 2nd element)
>>> translations[1::2]
(count from 1, every 2nd element)
This, of course, is to generate two parallel lists from your one.
"zip" well, *zips* two or more lists together:
>>> zip(translations[::2], translations[1::2])
Which is all ready for the dict constructor:
>>> dict(zip(translations[::2], translations[1::2]))
I always find it helps to take a statement apart in the interpreter if
-- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.comReceived on Thu Sep 29 16:41:17 2005 |