tags:

views:

78

answers:

1

Hi,

This should be a fairly straight forward python question, but I'm getting stuck getting the syntax right.

Let's say I have a string:

"1:a,b,c::2:e,f,g::3:h,i,j"

and I want to convert this to a map like so:

{'1': ['a', 'b', 'c'], '2': ['e', 'f', 'g'], '3': ['h', 'i', 'j']}

How would this be done?

I can figure out how to do it using nested for loops, but would be cool to just do it in a single line.

Thanks!

+8  A: 

Here's one approach:

dict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::')))
Mark Byers
Horrible names, but otherwise perfect, +1
delnan
@delnan: not quite perfect, use of `list()` is redundant
John Machin
@John Machin: Thanks for pointing that out. I wasn't sure if split returns a list in all versions of Python so was playing it safe. But I checked now and it seems that it always does. Fixed now. :)
Mark Byers
I wasn't sure either if split returned a list. They made nearly everything an iterator in Python 3 (which is a good thing) ;)
delnan