Splitting string into dictionary

David Pratt fairwinds at eastlink.ca
Fri Jul 1 01:35:44 EDT 2005


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.

Ok. So it is a list comprehension and then collection.  What is zip 
doing in the second line?

Regards
David

On Friday, July 1, 2005, at 02:11 AM, Robert Kern wrote:

> David Pratt wrote:
>> I have string text with language text records that looks like this:
>>
>> 'en' | 'the brown cow' | 'fr' | 'la vache brun'
>>
>> Two or more language records can exist in each string (example above
>> shows 2 - but could contain more)
>> The second vertical line character in the example above is the record
>> break in the pattern (between 'cow' and 'fr')
>>
>> What is the shortest route to getting this into a dictionary like:
>>
>> {'en':'the brown cow','fr':'la vache brun'}
>>
>> The language code is always 2 lower case letters.
>>
>> Many thanks.
>
> Ignore the last message.
>
> translations = [x.strip(" '") for x in line.split('|')]
> d = dict(zip(translations[::2], translations[1::2]))
>
> -- 
> Robert Kern
> rkern at ucsd.edu
>
> "In the fields of hell where the grass grows high
>   Are the graves of dreams allowed to die."
>    -- Richard Harter
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list