Splitting string into dictionary
Robert Kern
rkern at ucsd.edu
Fri Jul 1 01:08:36 EDT 2005
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.
translations = [x.strip(" '") for x in line.split('|')]
d = {}
for i in range(0, 2*len(translations), 2):
d[translations[i]] = translations[i+1]
--
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
More information about the Python-list
mailing list