Splitting string into dictionary

Terry Hancock hancock at anansispaceworks.com
Fri Jul 1 05:38:51 EDT 2005


On Friday 01 July 2005 12:35 am, David Pratt wrote:
> Wow Robert that is incredible python magic!  I am trying to figure out 
> what this is doing since my attempts were regex and some long string 
> splitting and collection.

Try it out in the interpreter:

Test data:
>>> test = "'en' | 'the brown cow' | 'fr' | 'la vache brun'"

Splitting, you already know:
>>> line.split('|')
["'en' ", " 'the brown cow' ", " 'fr' ", " 'la vache brun'"]

The list comprehension generates a new list based on the old one,
in this case, using the string method strip to remove spaces and
single quotes:

>>> translations = [x.strip(" '") for x in line.split('|')]
>>> translations
['en', 'the brown cow', 'fr', 'la vache brun']

Then Robert did some real magic by using extended slice notation:

>>> translations[::2]
['en', 'fr']

(count from 0, every 2nd element)

>>> translations[1::2]
['the brown cow', 'la vache brun']

(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])
[('en', 'the brown cow'), ('fr', 'la vache brun')]

Which is all ready for the dict constructor:

>>> dict(zip(translations[::2], translations[1::2]))
{'fr': 'la vache brun', 'en': 'the brown cow'}

I always find it helps to take a statement apart in the interpreter if
a little too much is going on in one line for me to follow.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list